首頁 > web前端 > js教程 > 主體

使用Ajax時Json-lib如何處理

php中世界最好的语言
發布: 2018-03-31 13:46:26
原創
1121 人瀏覽過

這次帶給大家使用Ajax時Json-lib如何處理,使用Ajax時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()); 
 }
}
登入後複製

我相信看了本文案例你已經掌握了方法,更多精彩請關注php中文網其它相關文章!

推薦閱讀:

用history讓ajax支援前進/後退/刷新

Ajax方法實作Form表單提交的方法

以上是使用Ajax時Json-lib如何處理的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新問題
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!