佳木斯湛栽影视文化发展公司

主頁 > 知識庫 > 使用Ajax或Easyui等框架時的Json-lib的處理方案

使用Ajax或Easyui等框架時的Json-lib的處理方案

熱門標簽:電子圍欄 科大訊飛語音識別系統(tǒng) Linux服務器 服務器配置 銀行業(yè)務 Mysql連接數(shù)設置 阿里云 團購網(wǎng)站

無論是使用ajax還是使用easyui等框架,后臺向前臺輸出數(shù)據(jù)時都涉及到json處理的問題,這里介紹兩種處理方法,第一種是手動配置json的處理方法,另一種使用json-lib的處理方案。普通手動配置方法比較笨拙,每次需要根據(jù)字段名逐個配置,因此也無法再其他對象上使用,降低了代碼的重用性,使用json-lib工具可以實現(xiàn)自動處理,針對不同的對象又不同的處理措施,大大提高了處理效率和代碼的重用性,以下分別根據(jù)案例介紹兩種方法的過程:

方法一:普通方法,通過手動配置轉(zhuǎn)型的過程,以easyui的請求方法為例,前臺通過dategrid向后臺請求用戶列表數(shù)據(jù),數(shù)據(jù)中存在普通字段(int、String)數(shù)據(jù),也有日期(date)數(shù)據(jù),

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">聯(lián)系電話/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));
 ListUser> userList=userService.findUserList(s_user, pageBean);
 Long total=userService.getUserCount(s_user);
 JSONObject result=new JSONObject();
 JSONArray jsonArray=JsonUtil.formatUserListToJsonArray(userList);
 //easyui接收屬性為rows(數(shù)據(jù)內(nèi)容)和total(總記錄數(shù))
 result.put("rows", jsonArray);
 result.put("total", total);
 //獲取response對象
 ResponseUtil.write(ServletActionContext.getResponse(), result);
}

*******************************************************************************************************************************************************

util工具:

public class JsonUtil {
  /**
   * 將List結(jié)果集轉(zhuǎn)化為JsonArray
   * @param gradeService
   * @param stuList
   * @return
   * @throws Exception
   */
  public static JSONArray formatUserListToJsonArray(ListUser> userList)throws Exception{
    JSONArray array=new JSONArray();
    for(int i=0;iuserList.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向后臺請求商品列表數(shù)據(jù),數(shù)據(jù)中存在普通字段(int、String)數(shù)據(jù),也有日期(date)數(shù)據(jù),同時商品對象(Product)還級聯(lián)了類別對象(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));
 ListProduct> productList=productService.getProducts(s_product, pageBean);
 long total=productService.getProductCount(s_product);
 
 //使用jsonLib工具將list轉(zhuǎn)為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(); 
 }
}
/**
 * 解決對象級聯(lián)問題
 * @author Administrator
 *
 */
public class ObjectJsonValueProcessor implements JsonValueProcessor{
 /**
 * 保留的字段
 */
 private String[] properties; 
 
 /**
 * 處理類型
 */
 private Class?> clazz; 
 
 /**
 * 構(gòu)造方法 
 * @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;iproperties.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的處理方案,希望對大家有所幫助,如果大家有任何疑問歡迎給我留言,小編會及時回復大家的!

您可能感興趣的文章:
  • json-lib將json格式的字符串,轉(zhuǎn)化為java對象的實例
  • Java 使用json-lib處理JSON詳解及實例代碼
  • json-lib出現(xiàn)There is a cycle in the hierarchy解決辦法
  • 將Java對象序列化成JSON和XML格式的實例
  • java將XML文檔轉(zhuǎn)換成json格式數(shù)據(jù)的示例
  • Java的微信開發(fā)中使用XML格式和JSON格式數(shù)據(jù)的示例
  • 解決使用json-lib包實現(xiàn)xml轉(zhuǎn)json時空值被轉(zhuǎn)為空中括號的問題

標簽:大理 廣元 棗莊 江蘇 衡水 萍鄉(xiāng) 衢州 蚌埠

巨人網(wǎng)絡通訊聲明:本文標題《使用Ajax或Easyui等框架時的Json-lib的處理方案》,本文關鍵詞  ;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P信息告之我們,我們將及時溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡,涉及言論、版權(quán)與本站無關。
  • 相關文章
  • 收縮
    • 微信客服
    • 微信二維碼
    • 電話咨詢

    • 400-1100-266
    石狮市| 金塔县| 城口县| 青田县| 德保县| 扎囊县| 黑水县| 旌德县| 塔河县| 张掖市| 内黄县| 青河县| 台北市| 古田县| 五家渠市| 山阳县| 内黄县| 云阳县| 山阴县| 个旧市| 陵川县| 盱眙县| 临朐县| 南城县| 南漳县| 衡阳县| 大英县| 新安县| 莱芜市| 昌宁县| 保山市| 博罗县| 天长市| 朝阳市| 五台县| 白水县| 肇庆市| 扬中市| 宝兴县| 永胜县| 富平县|