This time I will show you how to handle Json-lib when using Ajax. What are the precautions for Json-lib processing when using Ajax? The following is a practical case, let's take a look.
Whether you are using ajax or easyui and other frameworks, the problem of json processing is involved when the background outputs data to the front. Here are two processing methods. The first is to manually configure the json processing method, and the other is to manually configure the json processing method. A solution using json-lib. The ordinary manual configuration method is clumsy. It needs to be configured one by one according to the field name each time, so it cannot be used on other objects, which reduces the reusability of the code. The json-lib tool can be used to achieve automatic processing and different processing for different objects. Measures have greatly improved the processing efficiency and code reusability. The processes of the two methods are introduced below based on cases:
Method 1: Ordinary method, through the process of manual configuration transformation, request with easyui's
Method is an example. The frontend requests user list data from the backend through dategrid. There are ordinary field (int, String) data and date (date) data in the data.
jsp page:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | <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>
|
Copy after login
************************************************ *************************************************** *************************************************** ***
action layer:
1 2 3 4 5 6 7 8 9 10 11 12 | 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);
result.put( "rows" , jsonArray);
result.put( "total" , total);
ResponseUtil.write(ServletActionContext.getResponse(), result);
}
|
Copy after login
********************************** *************************************************** *************************************************** ********************
util tool:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | public class JsonUtil {
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());
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 ;
}
}
|
Copy after login
Method 2: Use the jsonLib tool to complete the processing, using the easyui request method For example, the frontend requests product list data from the backend through dategrid. There are ordinary field (int, String) data and date (date) data in the data. At the same time, the product object (Product) is also cascaded with the category object (ProductType)
jsp page:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | <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>
|
Copy after login
****************************************** *************************************************** *************************************************** ****************
action layer:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 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);
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 ));
JSONArray rows=JSONArray.fromObject(productList, jsonConfig);
JSONObject result= new JSONObject();
result.put( "rows" , rows);
result.put( "total" , total);
ResponseUtil.write(ServletActionContext.getResponse(), result);
}
|
Copy after login
******************** *************************************************** *************************************************** *******************************
util tool:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 |
public class DateJsonValueProcessor implements JsonValueProcessor{
private String format;
public DateJsonValueProcessor(String format){
this.format = format;
}
public Object processArrayValue(Object value, JsonConfig jsonConfig) {
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();
}
}
public class ObjectJsonValueProcessor implements JsonValueProcessor{
private String[] properties;
private Class<?> clazz;
public ObjectJsonValueProcessor(String[] properties,Class<?> clazz){
this.properties = properties;
this.clazz =clazz;
}
public Object processArrayValue(Object arg0, JsonConfig arg1) {
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());
}
}
|
Copy after login
I believe I saw it You have mastered the method in the case of this article. For more exciting information, please pay attention to other related articles on the php Chinese website!
Recommended reading:
Use history to enable ajax to support forward/back/refresh
Ajax method to implement Form form submission
The above is the detailed content of How does Json-lib handle when using Ajax. For more information, please follow other related articles on the PHP Chinese website!