用户登录
用户注册

分享至

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

  • 作者: 热情誓与天比高
  • 来源: 51数据库
  • 2021-08-29

无论是使用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的处理方案,希望对大家有所帮助

软件
前端设计
程序设计
Java相关