I have the following code and I would to achieve functionality that /getJson will return user object as json and /getJson2 will return user2 as Json object.
You must include all properties that you want to serialize. This includes the properties of the User class like this, for example:
@Action(value="/getJson", results = {
@Result(name="success", type="json",params = {
"includeProperties",
"user\.firstName, user\.lastName"})})
But, another form to get this work could be using regular expressions:
@Action(value="/getJson", results = {
@Result(name="success", type="json",params = {
"includeProperties",
"user\..*"})})
Regards.
Yes it is possible, the solution requires the use of include/exclude parameters.
Following is an example.
Methods getJson1 and getJson2 show includeParameters while getJson3 shows excludeParameters.
Note: Although the example uses strings as the arguments for include/exclude parameters the string is interpreted as a regular expression. So I could replace "string1, string2" on action3 with "string*".
For more information see: https://cwiki.apache.org/confluence/display/WW/JSON%20Plugin
package struts2;
import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
@ParentPackage("json-default")
public class Test2 extends ActionSupport {
private String string1 = "One";
private String string2 = "Two";
private String other = "Other";
public String getString1() {
return this.string1;
}
public String getString2() {
return this.string2;
}
public String getOther() {
return this.other;
}
@Action(value="/getJson1", results = {
@Result(type = "json", params = {
"includeProperties",
"string1"
})})
public String action1() {
return ActionSupport.SUCCESS;
}
@Action(value="/getJson2", results = {
@Result(type = "json", params = {
"includeProperties",
"string2"
})})
public String action2() {
return ActionSupport.SUCCESS;
}
@Action(value="/getJson3", results = {
@Result(type = "json", params = {
"excludeProperties",
"string1, string2"
})})
public String action3() {
return ActionSupport.SUCCESS;
}
}
.../getJson1 returns {"string1":"One"}
.../getJson2 returns {"string2":"Two"}
.../getJson3 returns {"other":"Other"}
This action provides two properties: user and user2.
If both /getJson and /getJson2 map to this action class, then they will both respond with the available properties: user and user2.