使用Ajax或Easyui等框架时的Json-lib的处理方案
发布时间 - 2026-01-11 02:02:26 点击率:次无论是使用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时空值被转为空中括号的问题
# 也有
# 两种
# 为例
# 小编
# 级联
# 给大家
# 又不
# 可以实现
# 涉及到
# 转化为
# 上架
# 所述
# 出生日期
# 第一种
# 给我留言
# 真实姓名
# 用户列表
# 有任何
# 提高了
# 字段名
相关栏目:
【
网站优化151355 】
【
网络推广146373 】
【
网络技术251813 】
【
AI营销90571 】
相关推荐:
教你用AI润色文章,让你的文字表达更专业
大连 网站制作,大连天途有线官网?
如何在IIS管理器中快速创建并配置网站?
如何用免费手机建站系统零基础打造专业网站?
如何在Windows服务器上快速搭建网站?
Linux网络带宽限制_tc配置实践解析【教程】
Win11应用商店下载慢怎么办 Win11更改DNS提速下载【修复】
绝密ChatGPT指令:手把手教你生成HR无法拒绝的求职信
品牌网站制作公司有哪些,买正品品牌一般去哪个网站买?
如何注册花生壳免费域名并搭建个人网站?
Claude怎样写约束型提示词_Claude约束提示词写法【教程】
Laravel怎么使用Collection集合方法_Laravel数组操作高级函数pluck与map【手册】
如何登录建站主机?访问步骤全解析
香港服务器网站测试全流程:性能评估、SEO加载与移动适配优化
Laravel如何处理CORS跨域问题_Laravel项目CORS配置与解决方案
SQL查询语句优化的实用方法总结
如何构建满足综合性能需求的优质建站方案?
个人摄影网站制作流程,摄影爱好者都去什么网站?
Windows10电脑怎么查看硬盘通电时间_Win10使用工具检测磁盘健康
通义万相免费版怎么用_通义万相免费版使用方法详细指南【教程】
如何在腾讯云服务器上快速搭建个人网站?
Laravel如何发送邮件_Laravel Mailables构建与发送邮件的简明教程
深圳网站制作平台,深圳市做网站好的公司有哪些?
如何制作新型网站程序文件,新型止水鱼鳞网要拆除吗?
Laravel如何使用Service Container和依赖注入?(代码示例)
Laravel怎么进行数据库事务处理_Laravel DB Facade事务操作确保数据一致性
制作旅游网站html,怎样注册旅游网站?
浅谈redis在项目中的应用
谷歌Google入口永久地址_Google搜索引擎官网首页永久入口
电商网站制作价格怎么算,网上拍卖流程以及规则?
如何在宝塔面板创建新站点?
百度输入法ai面板怎么关 百度输入法ai面板隐藏技巧
如何在橙子建站上传落地页?操作指南详解
如何在Windows 2008云服务器安全搭建网站?
猎豹浏览器开发者工具怎么打开 猎豹浏览器F12调试工具使用【前端必备】
如何正确下载安装西数主机建站助手?
关于BootStrap modal 在IOS9中不能弹出的解决方法(IOS 9 bootstrap modal ios 9 noticework)
Laravel Telescope怎么调试_使用Laravel Telescope进行应用监控与调试
Laravel如何生成和使用数据填充?(Seeder和Factory示例)
Laravel如何监控和管理失败的队列任务_Laravel失败任务处理与监控
如何在万网开始建站?分步指南解析
香港服务器部署网站为何提示未备案?
电视网站制作tvbox接口,云海电视怎样自定义添加电视源?
Laravel怎么使用Intervention Image库处理图片上传和缩放
齐河建站公司:营销型网站建设与SEO优化双核驱动策略
如何在云指建站中生成FTP站点?
Laravel怎么实现验证码功能_Laravel集成验证码库防止机器人注册
详解免费开源的DotNet二维码操作组件ThoughtWorks.QRCode(.NET组件介绍之四)
网站优化排名时,需要考虑哪些问题呢?
东莞专业网站制作公司有哪些,东莞招聘网站哪个好?

