You need the struts2-json-plugin.
It serves two main purposes:
#1 - Converting Java objects to JSON through the json
result (from Action to JSP);
#2 - Converting Javascript objects to JSON through the json
interceptor (from JSP to Action).
While the first is automatic, for the second (that is what you want) you need to define an interceptor stack containing the json
interceptor, for example:
<package name="myPackage" extends="json-default">
...
<action name="myAction" class="foo.bar.MyAction">
<interceptor-ref name="json" /> <!-- #2 is here -->
<interceptor-ref name="defaultStack" />
<result name="success" type="json"> <!-- #1 is here -->
<param name="root">myJavaObjectThatWillBecomeJson</param>
</result>
<result name="error">error.jsp</result>
</action>
...
After confirming that it is working, you can (and should) define the interceptor stack once in the configuration, setting it as the default interceptor, instead of rewriting this configuration inside every action.
For the json Interceptor to run properly, the conditions are:
- The "
content-type
" must be "application/json
"
- The JSON content must be well formed, see json.org for grammar.
- Action must have a public "setter" method for fields that must be populated.
- Supported types for population are: Primitives (int,long...String), Date, List, Map, Primitive Arrays, Other class
(more on this later), and Array of Other class.
- Any object in JSON, that is to be populated inside a list, or a map, will be of type Map (mapping from properties to values), any
whole number will be of type Long, any decimal number will be of type
Double, and any array of type List.