侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

使用Ajax或Easyui等框架时的Json-lib的处理方案

前端  /  管理员 发布于 3年前   131

无论是使用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的处理方案,希望对大家有所帮助,如果大家有任何疑问欢迎给我留言,小编会及时回复大家的!


  • 上一条:
    Python中elasticsearch插入和更新数据的实现方法
    下一条:
    详解Ajax跨域(jsonp) 调用JAVA后台
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 在js中使用URL类用来解析处理URL的示例代码(0个评论)
    • js中动画事件:requestAnimationFrame、transitionend、animation...(0个评论)
    • 在js中mouseover和 mouseenter的区别浅析(0个评论)
    • uniapp调用手机实现打电话录音功能示例代码(0个评论)
    • 在uniapp开发微信小程序中图片大小显示不正常解决方法(0个评论)
    • 近期文章
    • 在laravel框架中的5个HTTP客户端技巧分享(0个评论)
    • 在go语言中使用FFmpeg库实现PCM音频文件编码为mp3格式文件流程步骤(0个评论)
    • gopacket免安装Pcap实现驱动层流量抓包流程步骤(0个评论)
    • 在laravel项目中实现密码强度验证功能推荐扩展包:password-strength(0个评论)
    • 在go语言中用filepath.Match()函数以通配符模式匹配字符串示例(0个评论)
    • Laravel Response Classes 响应类使用优化浅析(0个评论)
    • mysql中sql_mode的各模式浅析(0个评论)
    • 百度文心一言今天发布,个人第一批内测体验记录,不好别打我(0个评论)
    • 嘿加密世界让我们谈谈在共识中将中本聪主流化(0个评论)
    • 在go语言中寻找两个切片或数组中的相同元素/共同点/交集并集示例代码(0个评论)
    • 近期评论
    • 博主 在

      2023年国务院办公厅春节放假通知:1月21日起休7天中评论 @ xiaoB 你只管努力,剩下的叫给天意;天若有情天亦老,..
    • xiaoB 在

      2023年国务院办公厅春节放假通知:1月21日起休7天中评论 会不会春节放假后又阳一次?..
    • BUG4 在

      你翻墙过吗?国内使用vpn翻墙可能会被网警抓,你需了解的事中评论 不是吧?..
    • 博主 在

      go语言+beego框架中获取get,post请求的所有参数中评论 @ t1  直接在router.go文件中配就ok..
    • Jade 在

      如何在MySQL查询中获得当月记录中评论 Dear zongscan.com team, We can skyroc..
    • 2016-11
    • 2017-06
    • 2017-07
    • 2017-08
    • 2017-09
    • 2017-10
    • 2017-11
    • 2018-03
    • 2018-04
    • 2018-05
    • 2018-06
    • 2018-09
    • 2018-11
    • 2018-12
    • 2019-02
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2021-04
    • 2021-05
    • 2021-07
    • 2021-08
    • 2021-09
    • 2021-10
    • 2021-11
    • 2022-08
    • 2022-09
    • 2022-10
    • 2022-11
    • 2022-12
    • 2023-01
    • 2023-02
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客