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

(0)

相关推荐

  • springMVC + easyui + $.ajaxFileUpload实现文件上传注意事项

    在使用easyUI做前端样式展示时,遇到了文件上传的问题,而且是在弹出层中提交表单,想做到不刷新页面,所以选择了使用ajaxFileUpload插件.提交表单时一直发现后台接收不到文件,后检查发现,原来是文件的id不对. 文件上传框我们定义如下: <input class="easyui-filebox" id="image" name="image" data-options="label:'产品图片:',buttonText:

  • jquery easyUI中ajax异步校验用户名

    以前无聊写过一个小东西,其中有一个功能就是添加用户,当时并没有考虑用户名重复的问题,今日闲来无事,打算利用ajax的异步刷新来校验用户名是否存在.自己也是新手,刚刚大三,哈哈写的不对的地方请指出. 放上效果图: 首先是编写前的准备 我并不是用原生的js来写的ajax而是用的jqueryeasyUI框架中的ajax,所以在使用之前就必须要引入jquery的js文件. <link rel="stylesheet" type="text/css" href=&quo

  • EasyUI框架 使用Ajax提交注册信息的实现代码

    EasyUI框架 使用Ajax提交注册信息的实现代码 一.服务器代码: @Controller @Scope("prototype") public class StudentAction extends BaseAction<Student> { private static final long serialVersionUID = -2612140283476148779L; private Logger logger = Logger.getLogger(Stude

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

    无论是使用ajax还是使用easyui等框架,后台向前台输出数据时都涉及到json处理的问题,这里介绍两种处理方法,第一种是手动配置json的处理方法,另一种使用json-lib的处理方案.普通手动配置方法比较笨拙,每次需要根据字段名逐个配置,因此也无法再其他对象上使用,降低了代码的重用性,使用json-lib工具可以实现自动处理,针对不同的对象又不同的处理措施,大大提高了处理效率和代码的重用性,以下分别根据案例介绍两种方法的过程: 方法一:普通方法,通过手动配置转型的过程,以easyui的请求

  • jQuery前端框架easyui使用Dialog时bug处理

    最近一直都在用easyui前端框架来开发设计UI,但在使用Dialog时,发现如果页面内容比较多,就会出现问题,首先看一下我的原代码: 复制代码 代码如下: <input type="button" value="确认预约" id="btnconfirm" onclick="javascript:openconfirmDlg();" />     <div id="confirmd">

  • asp.net省市三级联动的DropDownList+Ajax的三种框架(aspnet/Jquery/ExtJs)示例

    本文主要列举了省市三级联动的DropDownList+Ajax的三种框架(aspnet/Jquery/ExtJs)示例.前段时间需要作一个的Web前端应用,需要用多个框架,一个典型的应用场景是省市三级联动,基于此应用,特将三种主要的ajax框架略作整理,方便有需要的朋友查阅. 在示例之前,我们先设置一个演示数据源,新建一个项目,项目结构如图: 主要文件如下:AreaModel.cs: 复制代码 代码如下: using System; using System.Collections.Generi

  • IE浏览器与FF浏览器关于Ajax传递参数值为中文时的区别实例分析

    本文实例讲述了IE浏览器与FF浏览器关于Ajax传递参数值为中文时的区别.分享给大家供大家参考,具体如下: 前面介绍了<Javascript基于AJAX回调函数传递参数>,这里主要来分析一下ajax传递中文参数过程中针对不同浏览器的乱码处理方法. Ajax传递参数为中文时出现乱码,我遇到的情况是: 1.我的数据库连接 编码为 GB2312,latin1_swedish_ci 2.php 文件编码格式为 UTF-8,浏览器显示编码为 : UTF-8 3.我的页面显示方式为两种: 一)页面加载时自

  • jquery ajax多次请求数据时 不刷新问题的解决方法

    jquery的ajax在频繁请求数据,或者重复请求数据的时候出现了一个情况,那就是非ie浏览器正常,ie浏览器会设置缓存,导致第二次请求的时候不会刷新,系统报304 not modify, 解决方案: jquery的ajax方法提供配置参数:cache,(只需将属性设置为false即可) 详细: cache:Boolean 默认: true, dataType为"script"和"jsonp"时默认为false如果设置为 false ,浏览器将不缓存此页面. 以上就

  • Django添加bootstrap框架时无法加载静态文件的解决方式

    项目结构如下: 开始时在setting.py中设置如下; html文件中的写法如下: 这样设置一直无法加载静态文件,只需要修改setting.py文件如下: 就可以加载到静态文件了. 补充知识:Django-项目上线后,静态文件配置失效以及404.500页面的全局配置 一.项目上线后静态文件失效 1.因为项目还没上线的时候,django会默认从setting.py中这个设置 STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BAS

  • jQuery实现在下拉列表选择时获取json数据的方法

    本文实例讲述了jQuery实现在下拉列表选择时获取json数据的方法.分享给大家供大家参考.具体如下: function populateDropDown() { $.getJSON('/getData.aspx',{Name:$('#parm').val()},function(data){ var select = $('#DDLControl'); var options = select.attr('options'); $('option', select).remove(); $.e

  • centos安装jdk1.8时出现没有/lib/ld-linux.so.2:这个文件的原因分析

    -bash: /usr/local/jdk/jdk1.8.0_181/bin/java: /lib/ld-linux.so.2: bad ELF interpreter: No such file or directory 安装完后 java -version 查看版本出现: 原因是:没有那个文件或目录,找了很久发现需要安装glibc.i686 使用命令:sudo yum install glibc.i686 再次查看版本: 总结 以上所述是小编给大家介绍的centos安装jdk1.8时出现没有

  • jQuery结合AJAX之在页面滚动时从服务器加载数据

     简介 文本将演示怎么在滚动滚动条时从服务器端下载数据.用AJAX技术从服务器端加载数据有助于改善任何web应用的性能表现,因为在打开页面时,只有一屏的数据从服务器端加载了,需要更多的数据时,可以随着用户滚动滚动条再从服务器端加载. 背景 是Facebook促使我写出了在滚动条滚动时再从服务器加载数据的代码.浏览facebook时,我很惊讶的发现当我滚动页面时,新的来自服务器的数据开始插入到此现存的数据中.然后,对于用c#实现同样的功能,我在互联网上了查找了相关信息,但没有发现任何关于用c#实现

  • jQuery ajax 当async为false时解决同步操作失败的问题

    jQuery的ajax,当async为false时,同步操作失败.解决方案,jqueryasync 最近做项目遇到jQuery的ajax,当async为false时,同步操作失败的问题,上网搜索下,得到解决办法,这里就说下如何解决: 引发失败时代码: $.ajax({ url : 'your url', data:{name:value}, cache : false, async : true, type : "POST", dataType : 'json/xml/html', s

随机推荐