使用Ajax或Easyui等框架時(shí)的Json-lib的處理方案
無(wú)論是使用ajax還是使用easyui等框架,后臺(tái)向前臺(tái)輸出數(shù)據(jù)時(shí)都涉及到j(luò)son處理的問(wèn)題,這里介紹兩種處理方法,第一種是手動(dòng)配置json的處理方法,另一種使用json-lib的處理方案。普通手動(dòng)配置方法比較笨拙,每次需要根據(jù)字段名逐個(gè)配置,因此也無(wú)法再其他對(duì)象上使用,降低了代碼的重用性,使用json-lib工具可以實(shí)現(xiàn)自動(dòng)處理,針對(duì)不同的對(duì)象又不同的處理措施,大大提高了處理效率和代碼的重用性,以下分別根據(jù)案例介紹兩種方法的過(guò)程:
方法一:普通方法,通過(guò)手動(dòng)配置轉(zhuǎn)型的過(guò)程,以easyui的請(qǐng)求方法為例,前臺(tái)通過(guò)dategrid向后臺(tái)請(qǐng)求用戶(hù)列表數(shù)據(jù),數(shù)據(jù)中存在普通字段(int、String)數(shù)據(jù),也有日期(date)數(shù)據(jù),
jsp頁(yè)面:
<table id="dg" title="用戶(hù)管理" 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">編號(hào)</th> <th field="trueName" width="80" align="center">真實(shí)姓名</th> <th field="userName" width="80" align="center">用戶(hù)名</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">聯(lián)系電話</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(數(shù)據(jù)內(nèi)容)和total(總記錄數(shù)) result.put("rows", jsonArray); result.put("total", total); //獲取response對(duì)象 ResponseUtil.write(ServletActionContext.getResponse(), result); }
*******************************************************************************************************************************************************
util工具:
public class JsonUtil { /** * 將List結(jié)果集轉(zhuǎn)化為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()); //需手動(dòng)逐個(gè)配置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的請(qǐng)求方法為例,前臺(tái)通過(guò)dategrid向后臺(tái)請(qǐng)求商品列表數(shù)據(jù),數(shù)據(jù)中存在普通字段(int、String)數(shù)據(jù),也有日期(date)數(shù)據(jù),同時(shí)商品對(duì)象(Product)還級(jí)聯(lián)了類(lèi)別對(duì)象(ProductType)
jsp頁(yè)面:
<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">編號(hào)</th> <th field="proPic" width="60" align="center" formatter="formatProPic">商品圖片</th> <th field="name" width="150" align="center">商品名稱(chēng)</th> <th field="price" width="50" align="center">價(jià)格</th> <th field="stock" width="50" align="center">庫(kù)存</th> <th field="smallType.id" width="100" align="center" formatter="formatTypeId" hidden="true">所屬商品類(lèi)id</th> <th field="smallType.name" width="100" align="center" formatter="formatTypeName">所屬商品類(lèi)</th> <th field="description" width="50" align="center" hidden="true">描述</th> <th field="hotTime" width="50" align="center" hidden="true">上架時(shí)間</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轉(zhuǎn)為json JsonConfig jsonConfig=new JsonConfig(); jsonConfig.setExcludes(new String[]{"orderProductList"}); //非字符串對(duì)象不予處理 jsonConfig.registerJsonValueProcessor(java.util.Date.class, new DateJsonValueProcessor("yyyy-MM-dd")); //處理日期 jsonConfig.registerJsonValueProcessor(ProductType.class,new ObjectJsonValueProcessor(new String[]{"id","name"}, ProductType.class)); //處理類(lèi)別list對(duì)象 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 日期處理類(lèi) * @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(); } } /** * 解決對(duì)象級(jí)聯(lián)問(wèn)題 * @author Administrator * */ public class ObjectJsonValueProcessor implements JsonValueProcessor{ /** * 保留的字段 */ private String[] properties; /** * 處理類(lèi)型 */ private Class<?> clazz; /** * 構(gòu)造方法 * @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()); } }
以上所述是小編給大家介紹的使用Ajax或Easyui等框架時(shí)的Json-lib的處理方案,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)歡迎給我留言,小編會(huì)及時(shí)回復(fù)大家的!
- json-lib將json格式的字符串,轉(zhuǎn)化為java對(duì)象的實(shí)例
- Java 使用json-lib處理JSON詳解及實(shí)例代碼
- json-lib出現(xiàn)There is a cycle in the hierarchy解決辦法
- 將Java對(duì)象序列化成JSON和XML格式的實(shí)例
- java將XML文檔轉(zhuǎn)換成json格式數(shù)據(jù)的示例
- Java的微信開(kāi)發(fā)中使用XML格式和JSON格式數(shù)據(jù)的示例
- 解決使用json-lib包實(shí)現(xiàn)xml轉(zhuǎn)json時(shí)空值被轉(zhuǎn)為空中括號(hào)的問(wèn)題
相關(guān)文章
Ajax修改數(shù)據(jù)即時(shí)顯示篇實(shí)現(xiàn)代碼
上一篇我們講了如何使用ajax向數(shù)據(jù)庫(kù)添加數(shù)據(jù),今天我們要大家學(xué)習(xí)的課程是:使用ajax修改數(shù)據(jù)庫(kù)數(shù)據(jù),并在客戶(hù)網(wǎng)頁(yè)立即顯示新的內(nèi)容.當(dāng)然在修改的過(guò)程中同樣不會(huì)有刷新網(wǎng)頁(yè)的情況發(fā)生!2010-10-10菜鳥(niǎo)蔡之Ajax復(fù)習(xí)第一篇(后臺(tái)asp.net)(傳統(tǒng)的JavaScript方法實(shí)現(xiàn)Ajax功能)
Ajax是Asynchronous JavaScript and XML,其核心是通過(guò)XMLHttpRequest對(duì)象以一種異步的方式向服務(wù)器發(fā)送請(qǐng)求,并通過(guò)該對(duì)象接收請(qǐng)求返回的數(shù)據(jù),從而完成人機(jī)交互的數(shù)據(jù)操作(呵呵、、、說(shuō)的有點(diǎn)嚇人!)2012-11-11利用XMLHTTP實(shí)現(xiàn)的二級(jí)連動(dòng)Select
利用XMLHTTP實(shí)現(xiàn)的二級(jí)連動(dòng)Select...2006-09-09Ajax獲取php返回json數(shù)據(jù)動(dòng)態(tài)生成select下拉框的實(shí)例
今天小編就為大家分享一篇Ajax獲取php返回json數(shù)據(jù)動(dòng)態(tài)生成select下拉框的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-08-08Ajax in action 英文版配書(shū)源碼 下載
Ajax in action 英文版配書(shū)源碼 下載...2007-05-05