无论是使用ajax还是使用easyui等框架,后台向前台输出数据时都涉及到json处理的问题,这里介绍两种处理方法,第一种是手动配置json的处理方法,另一种使用json-lib的处理方案。普通手动配置方法比较笨拙,每次需要根据字段名逐个配置,因此也无法再其他对象上使用,降低了代码的重用性,使用json-lib工具可以实现自动处理,针对不同的对象又不同的处理措施,大大提高了处理效率和代码的重用性,以下分别根据案例介绍两种方法的过程:
方法一:普通方法,通过手动配置转型的过程,以easyui的请求方法为例,前台通过dategrid向后台请求用户列表数据,数据中存在普通字段(int、String)数据,也有日期(date)数据,
jsp页面:
<table id="dg" title="用户管理" class="easyui-datagrid"
fitColumns="true" pagination="true" rownumbers="true"
url="${pageContext.request.contextPath}/user_list.action" fit="true" toolbar="#tb">
<thead>
<tr>
<th field="cb" checkbox="true" align="center"></th>
<th field="id" width="50" align="center">编号</th>
<th field="trueName" width="80" align="center">真实姓名</th>
<th field="userName" width="80" align="center">用户名</th>
<th field="password" width="80" align="center">密码</th>
<th field="sex" width="50" align="center">性别</th>
<th field="birthday" width="100" align="center">出生日期</th>
<th field="identityId" width="130" align="center">身份证</th>
<th field="email" width="120" align="center">邮件</th>
<th field="mobile" width="80" align="center">联系电话</th>
<th field="address" width="100" align="center">家庭地址</th>
</tr>
</thead>
</table>
*******************************************************************************************************************************************************
action层:
public void list()throws Exception{
PageBean pageBean=new PageBean(Integer.parseInt(page), Integer.parseInt(rows));
List<User> userList=userService.findUserList(s_user, pageBean);
Long total=userService.getUserCount(s_user);
JSONObject result=new JSONObject();
JSONArray jsonArray=JsonUtil.formatUserListToJsonArray(userList);
//easyui接收属性为rows(数据内容)和total(总记录数)
result.put("rows", jsonArray);
result.put("total", total);
//获取response对象
ResponseUtil.write(ServletActionContext.getResponse(), result);
}
*******************************************************************************************************************************************************
util工具:
public class JsonUtil {
/**
* 将List结果集转化为JsonArray
* @param gradeService
* @param stuList
* @return
* @throws Exception
*/
public static JSONArray formatUserListToJsonArray(List<User> userList)throws Exception{
JSONArray array=new JSONArray();
for(int i=0;i<userList.size();i++){
User user=userList.get(i);
JSONObject jsonObject=new JSONObject();
jsonObject.put("userName", user.getUserName()); //需手动逐个配置json的key-code
jsonObject.put("password", user.getPassword());
jsonObject.put("trueName", user.getTrueName());
jsonObject.put("sex", user.getSex());
jsonObject.put("birthday", DateUtil.formatDate((user.getBirthday()), "yyyy-MM-dd"));
jsonObject.put("identityId", user.getIdentityId());
jsonObject.put("email", user.getEmail());
jsonObject.put("mobile", user.getMobile());
jsonObject.put("address", user.getAddress());
jsonObject.put("id", user.getId());
array.add(jsonObject);
}
return array;
}
}









