這篇文章給大家分享的是有關使用Ajax或Easyui等框架時Json-lib的示例分析的內容。小編覺得挺實用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。
無論是使用ajax還是使用easyui等框架,后臺向前臺輸出數據時都涉及到json處理的問題,這里介紹兩種處理方法,第一種是手動配置json的處理方法,另一種使用json-lib的處理方案。普通手動配置方法比較笨拙,每次需要根據字段名逐個配置,因此也無法再其他對象上使用,降低了代碼的重用性,使用json-lib工具可以實現自動處理,針對不同的對象又不同的處理措施,大大提高了處理效率和代碼的重用性,以下分別根據案例介紹兩種方法的過程:
方法一:普通方法,通過手動配置轉型的過程,以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>*******************************************************************************************************************************************************
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(數據內容)和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;
}
}方法二:使用jsonLib工具完成處理,以easyui的請求方法為例,前臺通過dategrid向后臺請求商品列表數據,數據中存在普通字段(int、String)數據,也有日期(date)數據,同時商品對象(Product)還級聯了類別對象(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>*******************************************************************************************************************************************************
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轉為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);
}*******************************************************************************************************************************************************
util工具:
/**
* 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());
}
}感謝各位的閱讀!關于“使用Ajax或Easyui等框架時Json-lib的示例分析”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,讓大家可以學到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。