无论是使用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;
}
}
方法二:使用jsonLib工具完成处理,以easyui的请求方法为例,前台通过dategrid向后台请求商品列表数据,数据中存在普通字段(int、String)数据,也有日期(date)数据,同时商品对象(Product)还级联了类别对象(ProductType)
jsp页面:
<table id="dg" title="商品管理" class="easyui-datagrid"
fitColumns="true" pagination="true" rownumbers="true"
url="${pageContext.request.contextPath}/product_list.action" fit="true" toolbar="#tb">
<thead>
<tr>
<th field="cb" checkbox="true" align="center"></th>
<th field="id" width="50" align="center" hidden="true">编号</th>
<th field="proPic" width="60" align="center" formatter="formatProPic">商品图片</th>
<th field="name" width="150" align="center">商品名称</th>
<th field="price" width="50" align="center">价格</th>
<th field="stock" width="50" align="center">库存</th>
<th field="smallType.id" width="100" align="center" formatter="formatTypeId" hidden="true">所属商品类id</th>
<th field="smallType.name" width="100" align="center" formatter="formatTypeName">所属商品类</th>
<th field="description" width="50" align="center" hidden="true">描述</th>
<th field="hotTime" width="50" align="center" hidden="true">上架时间</th>
</tr>
</thead>
</table>
*******************************************************************************************************************************************************
action层:
public void list() throws Exception{
PageBean pageBean=new PageBean(Integer.parseInt(page),Integer.parseInt(rows));
List<Product> productList=productService.getProducts(s_product, pageBean);
long total=productService.getProductCount(s_product);
//使用jsonLib工具将list转为json
JsonConfig jsonConfig=new JsonConfig();
jsonConfig.setExcludes(new String[]{"orderProductList"}); //非字符串对象不予处理
jsonConfig.registerJsonValueProcessor(java.util.Date.class, new DateJsonValueProcessor("yyyy-MM-dd")); //处理日期
jsonConfig.registerJsonValueProcessor(ProductType.class,new ObjectJsonValueProcessor(new String[]{"id","name"}, ProductType.class)); //处理类别list对象
JSONArray rows=JSONArray.fromObject(productList, jsonConfig);
JSONObject result=new JSONObject();
result.put("rows", rows);
result.put("total", total);
ResponseUtil.write(ServletActionContext.getResponse(), result);
}
*******************************************************************************************************************************************************
util工具:
/**
* json-lib 日期处理类
* @author Administrator
*
*/
public class DateJsonValueProcessor implements JsonValueProcessor{
private String format;
public DateJsonValueProcessor(String format){
this.format = format;
}
public Object processArrayValue(Object value, JsonConfig jsonConfig) {
// TODO Auto-generated method stub
return null;
}
public Object processObjectValue(String key, Object value, JsonConfig jsonConfig) {
if(value == null)
{
return "";
}
if(value instanceof java.sql.Timestamp)
{
String str = new SimpleDateFormat(format).format((java.sql.Timestamp)value);
return str;
}
if (value instanceof java.util.Date)
{
String str = new SimpleDateFormat(format).format((java.util.Date) value);
return str;
}
return value.toString();
}
}
/**
* 解决对象级联问题
* @author Administrator
*
*/
public class ObjectJsonValueProcessor implements JsonValueProcessor{
/**
* 保留的字段
*/
private String[] properties;
/**
* 处理类型
*/
private Class<?> clazz;
/**
* 构造方法
* @param properties
* @param clazz
*/
public ObjectJsonValueProcessor(String[] properties,Class<?> clazz){
this.properties = properties;
this.clazz =clazz;
}
public Object processArrayValue(Object arg0, JsonConfig arg1) {
// TODO Auto-generated method stub
return null;
}
public Object processObjectValue(String key, Object value, JsonConfig jsonConfig) {
PropertyDescriptor pd = null;
Method method = null;
StringBuffer json = new StringBuffer("{");
try{
for(int i=0;i<properties.length;i++){
pd = new PropertyDescriptor(properties[i], clazz);
method = pd.getReadMethod();
String v = String.valueOf(method.invoke(value));
json.append("'"+properties[i]+"':'"+v+"'");
json.append(i != properties.length-1?",":"");
}
json.append("}");
}catch (Exception e) {
e.printStackTrace();
}
return JSONObject.fromObject(json.toString());
}
}
以上所述是小编给大家介绍的使用Ajax或Easyui等框架时的Json-lib的处理方案,希望对大家有所帮助,如果大家有任何疑问欢迎给我留言,小编会及时回复大家的!
# ajax
# easyui框架
# json
# lib
# json-lib将json格式的字符串
# 转化为java对象的实例
# Java 使用json-lib处理JSON详解及实例代码
# json-lib出现There is a cycle in the hierarchy解决办法
# 将Java对象序列化成JSON和XML格式的实例
# java将XML文档转换成json格式数据的示例
# Java的微信开发中使用XML格式和JSON格式数据的示例
# 解决使用json-lib包实现xml转json时空值被转为空中括号的问题
# 也有
# 两种
# 为例
# 小编
# 级联
# 给大家
# 又不
# 可以实现
# 涉及到
# 转化为
# 上架
# 所述
# 出生日期
# 第一种
# 给我留言
# 真实姓名
# 用户列表
# 有任何
# 提高了
# 字段名
相关文章:
Android自定义控件实现温度旋转按钮效果
如何选择高效稳定的ISP建站解决方案?
广州网站制作的公司,现在专门做网站的公司有没有哪几家是比较好的,性价比高,模板也多的?
公司网站设计制作厂家,怎么创建自己的一个网站?
简历在线制作网站免费版,如何创建个人简历?
电视网站制作tvbox接口,云海电视怎样自定义添加电视源?
高端云建站费用究竟需要多少预算?
西安市网站制作公司,哪个相亲网站比较好?西安比较好的相亲网站?
宁波免费建站如何选择可靠模板与平台?
C++如何将C风格字符串(char*)转换为std::string?(代码示例)
建站主机选哪种环境更利于SEO优化?
如何选择美橙互联多站合一建站方案?
独立制作一个网站多少钱,建立网站需要花多少钱?
如何快速搭建高效WAP手机网站吸引移动用户?
官网网站制作腾讯审核要多久,联想路由器newifi官网
广州美橙建站如何快速搭建多端合一网站?
如何在景安云服务器上绑定域名并配置虚拟主机?
行程制作网站有哪些,第三方机票电子行程单怎么开?
如何访问已购建站主机并解决登录问题?
,sp开头的版面叫什么?
导航网站建站方案与优化指南:一站式高效搭建技巧解析
制作旅游网站html,怎样注册旅游网站?
安徽网站建设与外贸建站服务专业定制方案
制作门户网站的参考文献在哪,小说网站怎么建立?
建站主机解析:虚拟主机配置与服务器选择指南
MySQL查询结果复制到新表的方法(更新、插入)
如何在建站之星网店版论坛获取技术支持?
如何在阿里云虚拟服务器快速搭建网站?
如何在阿里云购买域名并搭建网站?
如何用好域名打造高点击率的自主建站?
合肥做个网站多少钱,合肥本地有没有比较靠谱的交友平台?
如何在阿里云虚拟主机上快速搭建个人网站?
北京制作网站的公司排名,北京三快科技有限公司是做什么?北京三快科技?
如何快速搭建高效服务器建站系统?
如何高效利用亚马逊云主机搭建企业网站?
学生网站制作软件,一个12岁的学生写小说,应该去什么样的网站?
如何快速辨别茅台真假?关键步骤解析
小程序网站制作需要准备什么资料,如何制作小程序?
沈阳个人网站制作公司,哪个网站能考到沈阳事业编招聘的信息?
建站之星如何助力网站排名飙升?揭秘高效技巧
如何在新浪SAE免费搭建个人博客?
网站制作多少钱一个,建一个论坛网站大约需要多少钱?
网站制作服务平台,有什么网站可以发布本地服务信息?
建站之星如何快速解决建站难题?
免费制作小说封面的网站有哪些,怎么接网站批量的封面单?
如何将凡科建站内容保存为本地文件?
实现虚拟支付需哪些建站技术支撑?
已有域名和空间如何快速搭建网站?
c# Task.Yield 的作用是什么 它和Task.Delay(1)有区别吗
如何通过建站之星自助学习解决操作问题?
*请认真填写需求信息,我们会在24小时内与您取得联系。