>  기사  >  웹 프론트엔드  >  Ajax를 사용할 때 Json-lib는 어떻게 처리합니까?

Ajax를 사용할 때 Json-lib는 어떻게 처리합니까?

php中世界最好的语言
php中世界最好的语言원래의
2018-03-31 13:46:261123검색

이번에는 Ajax 사용 시 Json-lib 처리 방법을 알려드리겠습니다. Ajax 사용 시 Json-lib 사용 시 주의사항은 무엇인지 살펴보겠습니다.

Ajax를 사용하든 easyui 및 기타 프레임워크를 사용하든 백그라운드에서 데이터를 전면으로 출력할 때 json 처리 문제가 발생합니다. 첫 번째는 json 처리 방법을 수동으로 구성하는 것이고, 다른 하나는 다음과 같습니다. json-lib 솔루션을 사용합니다. 일반적인 수동 구성 방법은 매번 필드 이름에 따라 하나씩 구성해야 하므로 다른 개체에 사용할 수 없으므로 json-lib 도구를 사용하면 자동으로 달성할 수 있습니다. 처리 효율성과 코드 재사용성이 크게 향상되었습니다. 사례에 따라 다음 두 가지 방법이 도입되었습니다.

방법 1: 일반적인 방법, 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>

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

액션 레이어:

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;
  }
}

방법 2: jsonLib 도구를 사용하여 처리를 완료합니다. easyui의 요청 방법을 예로 들면 프런트 데스크는 백엔드에서 제품 목록 데이터를 요청합니다. dategrid를 통해 데이터에는 일반 필드(int, String) 데이터와 날짜(date) 데이터가 동시에 카테고리 객체(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>

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

액션 레이어:

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);
}

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

유틸리티 도구:

/**
 * 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 중국어 웹사이트의 다른 관련 기사도 주목해주세요!

추천 자료:

기록을 사용하여 Ajax가 앞으로/뒤로/새로 고침을 지원하도록 활성화

Ajax 메서드를 사용하여 양식 제출 구현

위 내용은 Ajax를 사용할 때 Json-lib는 어떻게 처리합니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.