以前使用php的时候发现json的构造解析非常简单,但是呢,后来使用java的时候却发现java中要稍微复杂一点,所以呢在这里写一下我的实现方法
首先我是在这下面建了一个工具包,专门用来构造json的,代码
package com.test.tools;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletResponse;
import com.google.gson.Gson;
publicclassJSONUtils {
publicstaticvoidtoJson(HttpServletResponse response, Object data)
throws IOException {
Gson gson = new Gson();
String result = gson.toJson(data);
response.setContentType("text/json; charset=utf-8");
response.setHeader("Cache-Control","no-cache"); //取消浏览器缓存
PrintWriter out = response.getWriter();
out.print(result);
out.flush();
out.close();
}
}
这里使用的Gson,所以要报错,在lib中引用gson包
这里的gson包需要自己下载,然后引入,版本不一定是2.2.1
Action中的实现
首先引入工具包
import com.test.tools.JSONUtils;
public String test() throws Exception{
this.testList = UserDao.QueryAll("from User");
JSONUtils.toJson(ServletActionContext.getResponse(), userList);
return SUCCESS;
}
Struts.xml配置
<package name="struts" namespace="/" extends="struts-default,json-default">
<action name="index" class="com.test.action.UserAction" method="test">
<result type="json"><param name="root">jsonResult</param></result>
</action>
</package>
index.jsp
<table class="easyui-datagrid" title="UserInfo" style="width:100%;min-height:50px;"
data-options="singleSelect:true,collapsible:true,url:'index.action'">
<thead>
<tr>
<th data-options="field:'id',width:400">ID</th>
<th data-options="field:'username',width:400">username</th>
<th data-options="field:'userpwd',width:400">userpwd</th>
</tr>
</thead>
</table>
ok,现在信息就可以显示了!