Home > Guides > Plugin Developers Guide > JSON Plugin |
The JSON plugin provides a "json" result type that serializes actions into JSON. The serialization process is recursive, meaning that the whole object graph, starting on the action class (base class not included) will be serialized (root object can be customized using the "root" attribute). If the interceptor is used, the action will be populated from the JSON content in the request, these are the rules of the interceptor:
Given this JSON string:
The action must have a "setDoubleValue" method, taking either a "float" or a "double" argument (the interceptor will convert the value to the right one). There must be a "setNestedBean" whose argument type can be any class, that has a "setName" method taking as argument an "String". There must be a "setList" method that takes a "List" as argument, that list will contain: "A" (String), 10 (Long), 20.20 (Double), Map ("firstName" -> "El Zorro"). The "setArray" method can take as parameter either a "List", or any numeric array.
This plugin can be installed by copying the plugin jar into your application's /WEB-INF/lib
directory. No other files need to be copied or created.
To use maven, add this to your pom:
Use the JSON annotation to customize the serialization/deserialization process. Available JSON annotation fields:
Name | Description | Default Value | Serialization | Deserialization |
---|---|---|---|---|
name | Customize field name | empty | yes | no |
serialize | Include in serialization | true | yes | no |
deserialize | Include in deserialization | true | no | yes |
format | Format used to format/parse a Date field | "yyyy-MM-dd'T'HH:mm:ss" | yes | yes |
A comma-delimited list of regular expressions can be passed to the JSON Result and Interceptor, properties matching any of these regular expressions will be ignored on the serialization process:
A comma-delimited list of regular expressions can be passed to the JSON Result to restrict which properties will be serialized. ONLY properties matching any of these regular expressions will be included in the serialized output.
Use the "root" attribute(OGNL expression) to specify the root object to be serialized.
The "root" attribute(OGNL expression) can also be used on the interceptor to specify the object that must be populated, make sure this object is not null.
For several reasons you might want to wrap the JSON output with some text, like wrapping with comments, adding a prefix, or to use file uploads which require the result to be wrapped in a textarea. Use wrapPrefix to add content in the beginning and wrapPostfix to add content at the end. This settings take precedence over "wrapWithComments" and "prefix" which are deprecated from 0.34 on. Examples:
Wrap with comments:
Add a prefix:
Wrap for file upload:
If the serialized JSON is {name: 'El Zorro'}. Then the output will be: {}&& ({name: 'El Zorro'}
If the "wrapWithComments" (false by default) attribute is set to true, the generated JSON is wrapped with comments like:
To strip those comments use:
If the parameter prefix is set to true, the generated JSON will be prefixed with "{}&& ". This will help prevent hijacking. See this Dojo Ticket for details:
By default properties defined on base classes of the "root" object won't be serialized, to serialize properties in all base classes (up to Object) set "ignoreHierarchy" to false in the JSON result:
By default, an Enum is serialized as a name=value pair where value = name().
Use the "enumAsBean" result parameter to serialize Enum's as a bean with a special property _name with value name(). All properties of the enum are also serialized.
Enable this parameter through struts.xml:
Set the enableGZIP attribute to true to gzip the generated json response. The request must include "gzip" in the "Accept-Encoding" header for this to work.
Set noCache to true(false by default) to set the following headers in the response:
By default fields with null values are serialized like {property_name: null}. This can be prevented by setting excludeNullProperties to true.
Use statusCode to set the status of the response:
And errorCode to send an error(the server might end up sending something to the client which is not the serialized JSON):
To enable JSONP, set the parameter callbackParameter in either the JSON Result or the Interceptor. A parameter with that name will be read from the request, and it value will be used as the JSONP function. Assuming that a request is made with the parameter "callback"="exec":
And that the serialized JSON is {name: 'El Zorro'}. Then the output will be: exec({name: 'El Zorro'})
Content type will be set to application/json-rpc by default if SMD is being used, or application/json otherwise. Sometimes it is necessary to set the content type to something else, like when uploading files with Dojo and YUI. Use the contentType parameter in those cases.
User can define encoding per result or base on default assigned to struts.i18n.encoding. To define encoding for given result add encoding param as below:
This simple action has some fields:
Example:
Example with Convention Plugin Configuration:
Example with XML Configuration:
The json plugin can be used to execute action methods from javascript and return the output. This feature was developed with Dojo in mind, so it uses Simple Method Definition to advertise the remote service. Let's work it out with an example(useless as most examples).
First write the action:
Methods that will be called remotely must be annotated with the SMDMethod annotation, for security reasons. The method will take a bean object, modify its price and return it. The action can be annotated with the SMD annotation to customize the generated SMD (more on that soon), and parameters can be annotated with SMDMethodParameter. As you can see, we have a "dummy", smd method. This method will be used to generate the Simple Method Definition (a definition of all the services provided by this class), using the "json" result.
The bean class:
The mapping:
Nothing special here, except that both the interceptor and the result must be applied to the action, and "enableSMD" must be enabled for both.
Now the javascript code:
Dojo's JsonService will make a request to the action to load the SMD, which will return a JSON object with the definition of the available remote methods, using that information Dojo creates a "proxy" for those methods. Because of the asynchronous nature of the request, when the method is executed, a deferred object is returned, to which a callback function can be attached. The callback function will receive as a parameter the object returned from your action. That's it.
As annotations are not inherited in Java, some user might experience problems while trying to serialize objects that are proxied. eg. when you have attached AOP interceptors to your action.
In this situation, the plugin will not detect the annotations on methods in your action.
To overcome this, set the "ignoreInterfaces" result parameter to false (true by default) to request that the plugin inspects all interfaces and superclasses of the action for annotations on the action's methods.
NOTE: This parameter should only be set to false if your action could be a proxy as there is a performance cost caused by recursion through the interfaces.