最常用的返回json几种方式:
1.使用response的方式
public String putJson(Object obj){
PrintWriter pw = null;
try{
response.setContentType("application/json;charset=UTF-8");
pw = response.getWriter();
response.setDateHeader("Expires",0);
String jsonString = JSON.toJSONString(obj);
pw.write(jsonString);
pw.flush();
pw.close();
return CommonConstant.RESULT_SUCCESS;
}catch (Exception e){
logger.error("转换成JSON写入页面异常",e);
}
return CommonConstant.RESULT_FAIL;
}
2、使用json-default 的方式
使用这种方式的话需要添加json依赖
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-json-plugin</artifactId>
<version>2.3.16.3</version>
</dependency>
包要继承 json-default 使用 type="json"类型
result 表示需要返回的json数据
<package name="loginPackage" namespace="/" extends="json-default,struts-default">
<action name="login" class="loginAction" method="loginAction">
<result name="success" type="json">
<param name="root">result</param>
</result>
</action>
</package>
3、使用stream 返回json数据
这是xml 配置,使用 type="stream"
<action name="checkLogin" class="loginAction" method="checkLoginAction">
<result name="success" type="stream">
<param name="contentType">text/html</param>
<param name="inputName">stream</param>
</result>
</action>
这是action
public String checkLoginAction()throws Exception{
User user = new User();
user.setNickname("落叶");
user.setUsername("admin");
user.setPassword("123456");
String result = JSON.toJSONString(user);
stream = new ByteArrayInputStream(result.getBytes());
return "success";
}
这是返回结果