国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發 > AJAX > 正文

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

2024-09-01 08:30:47
字體:
來源:轉載
供稿:網友

無論是使用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的處理方案,希望對大家有所幫助,如果大家有任何疑問歡迎給我留言,小編會及時回復大家的!

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 巴楚县| 岳池县| 读书| 西丰县| 定西市| 平谷区| 娄烦县| 普格县| 兴隆县| 双鸭山市| 土默特左旗| 高邮市| 蒙山县| 新丰县| 深水埗区| 南昌市| 略阳县| 星子县| 突泉县| 渝北区| 牙克石市| 海安县| 株洲市| 天峻县| 库伦旗| 隆回县| 贵阳市| 永福县| 福建省| 开化县| 舒城县| 武城县| 永清县| 贞丰县| 乐清市| 合阳县| 清徐县| 清水河县| 庄河市| 临澧县| 长阳|