这篇文章主要介绍了使用ajax或easyui等框架时的Json-lib的处理方案 ,需要的朋友可以参考下
无论是使用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的处理方案(图文教程)的详细内容。更多信息请关注PHP中文网其他相关文章!

JavaScript在浏览器和Node.js环境中运行,依赖JavaScript引擎解析和执行代码。1)解析阶段生成抽象语法树(AST);2)编译阶段将AST转换为字节码或机器码;3)执行阶段执行编译后的代码。

Python和JavaScript的未来趋势包括:1.Python将巩固在科学计算和AI领域的地位,2.JavaScript将推动Web技术发展,3.跨平台开发将成为热门,4.性能优化将是重点。两者都将继续在各自领域扩展应用场景,并在性能上有更多突破。

Python和JavaScript在开发环境上的选择都很重要。1)Python的开发环境包括PyCharm、JupyterNotebook和Anaconda,适合数据科学和快速原型开发。2)JavaScript的开发环境包括Node.js、VSCode和Webpack,适用于前端和后端开发。根据项目需求选择合适的工具可以提高开发效率和项目成功率。

是的,JavaScript的引擎核心是用C语言编写的。1)C语言提供了高效性能和底层控制,适合JavaScript引擎的开发。2)以V8引擎为例,其核心用C 编写,结合了C的效率和面向对象特性。3)JavaScript引擎的工作原理包括解析、编译和执行,C语言在这些过程中发挥关键作用。

JavaScript是现代网站的核心,因为它增强了网页的交互性和动态性。1)它允许在不刷新页面的情况下改变内容,2)通过DOMAPI操作网页,3)支持复杂的交互效果如动画和拖放,4)优化性能和最佳实践提高用户体验。

C 和JavaScript通过WebAssembly实现互操作性。1)C 代码编译成WebAssembly模块,引入到JavaScript环境中,增强计算能力。2)在游戏开发中,C 处理物理引擎和图形渲染,JavaScript负责游戏逻辑和用户界面。

JavaScript在网站、移动应用、桌面应用和服务器端编程中均有广泛应用。1)在网站开发中,JavaScript与HTML、CSS一起操作DOM,实现动态效果,并支持如jQuery、React等框架。2)通过ReactNative和Ionic,JavaScript用于开发跨平台移动应用。3)Electron框架使JavaScript能构建桌面应用。4)Node.js让JavaScript在服务器端运行,支持高并发请求。

Python更适合数据科学和自动化,JavaScript更适合前端和全栈开发。1.Python在数据科学和机器学习中表现出色,使用NumPy、Pandas等库进行数据处理和建模。2.Python在自动化和脚本编写方面简洁高效。3.JavaScript在前端开发中不可或缺,用于构建动态网页和单页面应用。4.JavaScript通过Node.js在后端开发中发挥作用,支持全栈开发。


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

DVWA
Damn Vulnerable Web App (DVWA) 是一个PHP/MySQL的Web应用程序,非常容易受到攻击。它的主要目标是成为安全专业人员在合法环境中测试自己的技能和工具的辅助工具,帮助Web开发人员更好地理解保护Web应用程序的过程,并帮助教师/学生在课堂环境中教授/学习Web应用程序安全。DVWA的目标是通过简单直接的界面练习一些最常见的Web漏洞,难度各不相同。请注意,该软件中

EditPlus 中文破解版
体积小,语法高亮,不支持代码提示功能

MinGW - 适用于 Windows 的极简 GNU
这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。

SecLists
SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

记事本++7.3.1
好用且免费的代码编辑器