Json-lib processing scheme when Ajax or Easyui framework is used, easyuijson-lib
Whether ajax or easyui framework is used, json processing is involved when the background outputs data to the foreground. Here we introduce two processing methods. The first is to manually configure the json processing method, another solution is to use json-lib. The normal manual configuration method is clumsy. You need to configure the configuration one by one based on the field name each time, so you cannot use other objects. This reduces the reusability of the code and enables automatic processing using the json-lib tool, different Processing Methods for different objects greatly improve the processing efficiency and code reusability. The following describes the process of the two methods based on the case:
Method 1: the common method is to manually configure the transformation process. Taking the easyui request method as an example, the foreground requests the user list data from the background through dategrid. The data contains common fields (int and String) data, also has date 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"> NO. </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 card </th> <th field =" email "width =" 120 "align =" center "> email </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); // The easyui receiving attribute is rows (data content) and total (total number of records) result. put ("rows", jsonArray); result. put ("total", total); // gets the response object ResponseUtil. write (ServletActionContext. getResponse (), result );}
**************************************** **************************************** **************************************** *******************************
Util tool:
Public class JsonUtil {/*** converts the 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 (); // You must manually configure json key-code jsonObject one by one. 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: The jsonLib tool is used for processing. The easyui request method is used as an example. The foreground uses dategrid to request the product list data from the background. Common fields (int and String) exist in the data, there are also date data, and the Product also cascade 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"> product images </th> <th field = "name" width = "150" align = "center"> item Name </th> <th field = "price" width = "50" align = "center"> price </th> <th field = "stock" width = "50 "align =" center "> Inventory </th> <th field =" smallType. id "width =" 100 "align =" center "formatter =" formatTypeId "hidden =" true "> product category id </th> <th field =" smallType. name "width =" 100 "align =" center "formatter =" formatTypeName "> product class </th> <th field =" description "width =" 50 "align =" center "hidden =" true "> description </th> <th field =" hotTime "width =" 50 "align =" center "hidden =" true "> mounting time </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); // use the jsonLib tool to convert list to json JsonConfig jsonConfig = new JsonConfig (); jsonConfig. setExcludes (new String [] {"orderProductList"}); // jsonConfig is not processed for non-String objects. 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 object JSONArray rows = JSONArray. fromObject (productList, jsonConfig); JSONObject result = new JSONObject (); result. put ("rows", rows); result. put ("total", total); ResponseUtil. write (ServletActionContext. getResponse (), result );}
**************************************** **************************************** **************************************** *******************************
Util 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 j SonConfig) {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 () ;}}/*** solves the object cascade problem * @ author Administrator **/public class ObjectJsonV AlueProcessor implements JsonValueProcessor {/*** reserved field */private String [] properties;/*** processing type */private Class <?> Clazz;/*** constructor * @ 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 ());}}
The above section describes the Json-lib processing solution when using Ajax or Easyui frameworks. I hope it will be helpful to you. If you have any questions, please leave a message, the editor will reply to you in time!