1.需要jar包:struts2-json-plugin-2.5.5.jar
2.重写继承的package:<package name="default" namespace="/" extends="json-default">, json-default包已继承defaultPackage.
3.action配置:
<action name="testJson" class="helloWorldAction" method="json">
<result type="json">
<param name="root">jsonResult</param>
</result>
</action>
4.action增加成员变量jsonResult并增加getter
5.传输对象
calss JSONResult
boolean success;
Object data;
String error;
getter,setter...
6.示例:
public String json()
{
Employee e = new Employee();
e.setName("xx");
e.setAge(20);
e.setBrithday(new Date());
e.setSalary(6666d);
Employee e1 = new Employee();
e1.setName("yy");
e1.setAge(20);
e1.setBrithday(new Date());
e1.setSalary(6666d);
Employee e2 = new Employee();
e2.setName("zz");
e2.setAge(20);
e2.setBrithday(new Date());
e2.setSalary(6666d);
List<Employee> list = new ArrayList<Employee>();
list.add(e);
list.add(e1);
list.add(e2);
jsonResult.setData(list);
return SUCCESS;
}
http://localhost:8080/SSMProject/testJson
{
"data":
[{"age":20,"brithday":"2017-03-18T18:34:30","id":null,"name":"xx","salary":6666.0},
{"age":20,"brithday":"2017-03-18T18:34:30","id":null,"name":"yy","salary":6666.0},
{"age":20,"brithday":"2017-03-18T18:34:30","id":null,"name":"zz","salary":6666.0}],
"error":null,
"success":true
}