1、在Maven的pom.xml中引入对struts2-json-plugin-version.jar包的依赖;
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-json-plugin</artifactId>
<version>${struts2.json.plugin.version}</version>
</dependency>
<struts2.json.plugin.version>2.3.16</struts2.json.plugin.version>
2、Action类必须指定ParentPackage为:json-default;
@ParentPackage(value = "json-default")
public class TestAction extends ActionSupport {/*省略*/}
3、为Action类增加Map<String,Object>类型的属性;
private Map<String, Object> dataMap;
public Map<String, Object> getDataMap() {
return dataMap;
}
public void setDataMap(Map<String, Object> dataMap) {
this.dataMap = dataMap;
}
4、通过Annotation对Action类的相关方法进行JSON的注解。
@Action(className = "testAction", value = "/GetUserByName",
results = @Result(type = "json", params = {
"noCache", "true", // 是否启用缓存
"enableGZIP", "true", // 是否对响应JSON启用GZIP
"contentType", "text/html",// 设置响应的内容类型
"root", "dataMap", // 设置根对象
"ignoreHierarchy", "true" // 忽略基类
}))
public String getUserByName() {
User user = userService.getUserByName(userName);
dataMap = new HashMap<String, Object>();
dataMap.put("user", user);
return SUCCESS;
}
5、响应的JSON格式如下:
{"user":{"age":29,"firstName":"xiaojian","id":7,"lastName":"du"}}