Json-lib handling when using frameworks such as ajax or easyui

Keywords: JSON Java JSP Mobile

Whether using a framework such as ajax or easyui, the background output of data to the foreground involves JSON processing. Two processing methods are described here, one is to manually configure the JSON processing method, the other is to use json-lib processing method.The general manual configuration method is rather clumsy, and needs to be configured one by one according to the field name each time. Therefore, it can no longer be used on other objects, which reduces the reuse of code. Using json-lib tool can achieve automatic processing. Different processing measures for different objects can greatly improve the processing efficiency and the reuse of code. The following two methods are described separately according to the cases.Cheng:

Method 1: General method, by manually configuring the transformation process, taking easyui's request method as an example, the foreground requests user list data from the background through dategrid. There are common field (int, String) data and date data in the data.

jsp page:

<table id="dg" title="user management" 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">number</th>
			<th field="trueName" width="80" align="center">Real name</th>
			<th field="userName" width="80" align="center">User name</th>
			<th field="password" width="80" align="center">Password</th>
			<th field="sex" width="50" align="center">Gender</th>
			<th field="birthday" width="100" align="center">Date of birth</th>
			<th field="identityId" width="130" align="center">ID</th>
			<th field="email" width="120" align="center">mail</th>
			<th field="mobile" width="80" align="center">Contact number</th>
			<th field="address" width="100" align="center">Home Address</th>
		</tr>
	</thead>
</table>

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

action layer:

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 receive properties are rows (data content) and total (total number of records)
	result.put("rows", jsonArray);
	result.put("total", total);
	//Get response object
	ResponseUtil.write(ServletActionContext.getResponse(), result);
}

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

Utl Tool:

public class JsonUtil {
    /**
     * Convert List result set to 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's key-code needs to be manually configured one by one
            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;
    }
}

Method 2: Use the jsonLib tool to complete the processing. Take easyui's request method as an example. The foreground requests commodity list data from the background through dategrid. There are common field (int, String) and date data in the data, and commodity object (Product) also cascades the category object (ProductType)

jsp page:

<table id="dg" title="Commodity Management" 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">number</th>
		<th field="proPic" width="60" align="center" formatter="formatProPic">Merchandise Picture</th>
		<th field="name" width="150" align="center">Commodity Name</th>
		<th field="price" width="50" align="center">Price</th>
		<th field="stock" width="50" align="center">Stock</th>
		<th field="smallType.id" width="100" align="center" formatter="formatTypeId" hidden="true">Subordinate commodities id</th>
		<th field="smallType.name" width="100" align="center" formatter="formatTypeName">Subordinate commodities</th>
		<th field="description" width="50" align="center" hidden="true">describe</th>
		<th field="hotTime" width="50" align="center" hidden="true">Time on shelf</th>
	</tr>
	</thead>
</table>

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

action layer:

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);
		
	//Convert list to json using the jsonLib tool
	JsonConfig jsonConfig=new JsonConfig();
	jsonConfig.setExcludes(new String[]{"orderProductList"});  //Non-string objects will not be processed
	jsonConfig.registerJsonValueProcessor(java.util.Date.class, new DateJsonValueProcessor("yyyy-MM-dd"));  //Processing Date
	jsonConfig.registerJsonValueProcessor(ProductType.class,new ObjectJsonValueProcessor(new String[]{"id","name"}, ProductType.class));  //Processing category list objects
	JSONArray rows=JSONArray.fromObject(productList, jsonConfig);
	JSONObject result=new JSONObject();
	result.put("rows", rows);
	result.put("total", total);
	ResponseUtil.write(ServletActionContext.getResponse(), result);
}

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

Utl Tool:

/**
 * json-lib Date Processing Class
 * @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(); 
	}

}

/**
 * Solve cascading of objects
 * @author Administrator
 *
 */
public class ObjectJsonValueProcessor implements JsonValueProcessor{

	/**
	 * Reserved fields
	 */
	private String[] properties;  
	
	/**
	 * Processing Type
	 */
	private Class<?> clazz;  
	
	/**
	 * Construction method 
	 * @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());  
	}

}





Posted by camoconnell.com on Wed, 19 Jun 2019 09:26:14 -0700