Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * $Id: JSONResult.java 1421740 2012-12-14 08:53:49Z lukaszlenart $
   *
   * Licensed to the Apache Software Foundation (ASF) under one
   * or more contributor license agreements.  See the NOTICE file
   * distributed with this work for additional information
   * regarding copyright ownership.  The ASF licenses this file
   * to you under the Apache License, Version 2.0 (the
   * "License"); you may not use this file except in compliance
  * with the License.  You may obtain a copy of the License at
  *
  *  http://www.apache.org/licenses/LICENSE-2.0
  *
  * Unless required by applicable law or agreed to in writing,
  * software distributed under the License is distributed on an
  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  * KIND, either express or implied.  See the License for the
  * specific language governing permissions and limitations
  * under the License.
  */
 package org.apache.struts2.json;
 
 
 import java.util.List;
 import java.util.Set;

This result serializes an action into JSON.

Result parameters:

  • excludeProperties - list of regular expressions matching the properties to be excluded. The regular expressions are evaluated against the OGNL expression representation of the properties.

Example:

 <!-- START SNIPPET: example -->
 <result name="success" type="json" />
 <!-- END SNIPPET: example -->
 
 
 public class JSONResult implements Result {
 
     private static final long serialVersionUID = 8624350183189931165L;
 
     private static final Logger LOG = LoggerFactory.getLogger(JSONResult.class);
 
     private String encoding;
     private String defaultEncoding = "ISO-8859-1";
     private List<PatternincludeProperties;
     private List<PatternexcludeProperties;
     private String root;
     private boolean wrapWithComments;
     private boolean prefix;
     private boolean enableSMD = false;
     private boolean enableGZIP = false;
     private boolean ignoreHierarchy = true;
     private boolean ignoreInterfaces = true;
     private boolean enumAsBean = .;
     private boolean noCache = false;
     private boolean excludeNullProperties = false;
     private int statusCode;
     private int errorCode;
     private String callbackParameter;
     private String contentType;
     private String wrapPrefix;
     private String wrapSuffix;
 
     public void setDefaultEncoding(String val) {
         this. = val;
     }

    
Gets a list of regular expressions of properties to exclude from the JSON output.

Returns:
A list of compiled regular expression patterns
 
        return this.;
    }

    
Sets a comma-delimited list of regular expressions to match properties that should be excluded from the JSON output.

Parameters:
commaDelim A comma-delimited list of regular expressions
    public void setExcludeProperties(String commaDelim) {
        Set<StringexcludePatterns = JSONUtil.asSet(commaDelim);
        if (excludePatterns != null) {
            this. = new ArrayList<Pattern>(excludePatterns.size());
            for (String pattern : excludePatterns) {
                this..add(Pattern.compile(pattern));
            }
        }
    }

    
Sets a comma-delimited list of wildcard expressions to match properties that should be excluded from the JSON output.

Parameters:
commaDelim A comma-delimited list of wildcard patterns
    public void setExcludeWildcards(String commaDelim) {
        Set<StringexcludePatterns = JSONUtil.asSet(commaDelim);
        if (excludePatterns != null) {
            this. = new ArrayList<Pattern>(excludePatterns.size());
            for (String pattern : excludePatterns) {
                this..add(WildcardUtil.compileWildcardPattern(pattern));
            }
        }
    }

    

Returns:
the includeProperties
        return ;
    }

    
Sets a comma-delimited list of regular expressions to match properties that should be included in the JSON output.

Parameters:
commaDelim A comma-delimited list of regular expressions
    public void setIncludeProperties(String commaDelim) {
         = JSONUtil.processIncludePatterns(JSONUtil.asSet(commaDelim), .);
    }

    
Sets a comma-delimited list of wildcard expressions to match properties that should be included in the JSON output.

Parameters:
commaDelim A comma-delimited list of wildcard patterns
    public void setIncludeWildcards(String commaDelim) {
         = JSONUtil.processIncludePatterns(JSONUtil.asSet(commaDelim), .);
    }
    public void execute(ActionInvocation invocationthrows Exception {
        ActionContext actionContext = invocation.getInvocationContext();
        HttpServletRequest request = (HttpServletRequestactionContext.get(.);
        HttpServletResponse response = (HttpServletResponseactionContext.get(.);
        try {
            Object rootObject;
            rootObject = readRootObject(invocation);
            writeToResponse(responsecreateJSONString(requestrootObject), enableGzip(request));
        } catch (IOException exception) {
            .error(exception.getMessage(), exception);
            throw exception;
        }
    }
    protected Object readRootObject(ActionInvocation invocation) {
        if () {
            return buildSMDObject(invocation);
        }
        return findRootObject(invocation);
    }
    protected Object findRootObject(ActionInvocation invocation) {
        Object rootObject;
        if (this. != null) {
            ValueStack stack = invocation.getStack();
            rootObject = stack.findValue();
        } else {
            rootObject = invocation.getStack().peek(); // model overrides action
        }
        return rootObject;
    }
    protected String createJSONString(HttpServletRequest requestObject rootObjectthrows JSONException {
        json = addCallbackIfApplicable(requestjson);
        return json;
    }
    protected boolean enableGzip(HttpServletRequest request) {
        return  && JSONUtil.isGzipInRequest(request);
    }
    protected void writeToResponse(HttpServletResponse responseString jsonboolean gzipthrows IOException {
        JSONUtil.writeJSONToResponse(new SerializationParams(responsegetEncoding(), isWrapWithComments(),
                jsonfalsegzip,
                ));
    }
    @SuppressWarnings("unchecked")
    protected org.apache.struts2.json.smd.SMD buildSMDObject(ActionInvocation invocation) {
        return new SMDGenerator(findRootObject(invocation), ).generate(invocation);
    }

    
Retrieve the encoding

Returns:
The encoding associated with this template (defaults to the value of param 'encoding', if empty default to 'struts.i18n.encoding' property)
    protected String getEncoding() {
        String encoding = this.;
        if (encoding == null) {
            encoding = this.;
        }
        if (encoding == null) {
            encoding = System.getProperty("file.encoding");
        }
        if (encoding == null) {
            encoding = "UTF-8";
        }
        return encoding;
    }
    protected String addCallbackIfApplicable(HttpServletRequest requestString json) {
        if (( != null) && (.length() > 0)) {
            String callbackName = request.getParameter();
            if ((callbackName != null) && (callbackName.length() > 0))
                json = callbackName + "(" + json + ")";
        }
        return json;
    }

    

Returns:
OGNL expression of root object to be serialized
    public String getRoot() {
        return this.;
    }

    
Sets the root object to be serialized, defaults to the Action

Parameters:
root OGNL expression of root object to be serialized
    public void setRoot(String root) {
        this. = root;
    }

    

Returns:
Generated JSON must be enclosed in comments
    public boolean isWrapWithComments() {
        return this.;
    }

    
Wrap generated JSON with comments

Parameters:
wrapWithComments
    public void setWrapWithComments(boolean wrapWithComments) {
        this. = wrapWithComments;
    }

    

Returns:
Result has SMD generation enabled
    public boolean isEnableSMD() {
        return this.;
    }

    
Enable SMD generation for action, which can be used for JSON-RPC

Parameters:
enableSMD
    public void setEnableSMD(boolean enableSMD) {
        this. = enableSMD;
    }
    public void setIgnoreHierarchy(boolean ignoreHierarchy) {
        this. = ignoreHierarchy;
    }

    
Controls whether interfaces should be inspected for method annotations You may need to set to this true if your action is a proxy as annotations on methods are not inherited
    public void setIgnoreInterfaces(boolean ignoreInterfaces) {
        this. = ignoreInterfaces;
    }

    
Controls how Enum's are serialized : If true, an Enum is serialized as a name=value pair (name=name()) (default) If false, an Enum is serialized as a bean with a special property _name=name()

Parameters:
enumAsBean
    public void setEnumAsBean(boolean enumAsBean) {
        this. = enumAsBean;
    }
    public boolean isEnumAsBean() {
        return ;
    }
    public boolean isEnableGZIP() {
        return ;
    }
    public void setEnableGZIP(boolean enableGZIP) {
        this. = enableGZIP;
    }
    public boolean isNoCache() {
        return ;
    }

    
Add headers to response to prevent the browser from caching the response

Parameters:
noCache
    public void setNoCache(boolean noCache) {
        this. = noCache;
    }
    public boolean isIgnoreHierarchy() {
        return ;
    }
    public boolean isExcludeNullProperties() {
        return ;
    }

    
Do not serialize properties with a null value

Parameters:
excludeNullProperties
    public void setExcludeNullProperties(boolean excludeNullProperties) {
        this. = excludeNullProperties;
    }

    
Status code to be set in the response

Parameters:
statusCode
    public void setStatusCode(int statusCode) {
        this. = statusCode;
    }

    
Error code to be set in the response

Parameters:
errorCode
    public void setErrorCode(int errorCode) {
        this. = errorCode;
    }
    public void setCallbackParameter(String callbackParameter) {
        this. = callbackParameter;
    }
    public String getCallbackParameter() {
        return ;
    }

    
Prefix JSON with "{} &&"

Parameters:
prefix
    public void setPrefix(boolean prefix) {
        this. = prefix;
    }

    
Content type to be set in the response

Parameters:
contentType
    public void setContentType(String contentType) {
        this. = contentType;
    }
    public String getWrapPrefix() {
        return ;
    }

    
Text to be inserted at the begining of the response
    public void setWrapPrefix(String wrapPrefix) {
        this. = wrapPrefix;
    }
    public String getWrapSuffix() {
        return ;
    }

    
Text to be inserted at the end of the response
    public void setWrapSuffix(String wrapSuffix) {
        this. = wrapSuffix;
    }

    
If defined will be used instead of defaultEncoding, you can define it with result <result name="success" type="json"> <param name="encoding">UTF-8</param> </result>

Parameters:
encoding valid encoding string
    public void setEncoding(String encoding) {
        this. = encoding;
    }
New to GrepCode? Check out our FAQ X