To add Ashish to the answer, i.e. after adding struts2-json-plugin.
I like to use struts2-conions-plugin where possible, so I have very little in my struts.xml and prefer to use mostly annotations instead.
In order for your action to be returned by json when using conventions, there are two steps: 1) for your action to use the json-default package, 2) Define the action as having a json result type.
JSON annotation example
package org.test.action; import com.opensymphony.xwork2.ActionSupport; import org.apache.struts2.convention.annotation.ParentPackage; import org.apache.struts2.convention.annotation.Result; @ParentPackage("json-default") @Result(type = "json") public class JsonTest extends ActionSupport{ private String name = "Hello World"; private String language = "Java, I mean English"; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getLanguage() { return language; } public void setLanguage(String language) { this.language = language; } }
Sometimes the values ββare more complex than the primitives, and you want to trim the returned json, or sometimes you need to put several actions in one class (sometimes you return a complex structure and, by trimming it in a certain way, you can make your work with the client easier). To do this, we use include or exclude parameters.
Language Exception Example
Modify the above annotation of the result:
@Result(type = "json", params = { "excludeProperties", "language"})
Another way to achieve the above is to explicitly indicate what properties we want:
@Result(type = "json", params = { "includeProperties", "name"})
Example Using wild cards with exclude parameter No action code specified, useful for cropping complex objects
@Result(type = "json", params = { "excludeProperties", "punches.*.punchesCollection, *.punchesCollection.*"})
With the plugin, you can see that it is rather complicated than the xml method or annotations.