1. 程式人生 > >jsonConfig處理日期及對象級聯問題

jsonConfig處理日期及對象級聯問題

class text util big view small 構造 count ==

項目中經常用到ajax請求後臺,返回給前臺json對象字符串。有些實體包含字段可能有日期、list、以及級聯對象情況。因此,我們需要有針對性處理,

例如日期date類型,我們要給它轉為我們所想要的格式的日期字符串,返回給前臺。list我們要去除掉,級聯對象,只提取我們所需要的字段值。

例如實體product:

技術分享
  1 /**
  2  * 
  3  */
  4 package com.hik.entity;
  5 
  6 import java.util.ArrayList;
  7 import java.util.Date;
  8 import java.util.List;
9 10 import javax.persistence.Column; 11 import javax.persistence.Entity; 12 import javax.persistence.GeneratedValue; 13 import javax.persistence.Id; 14 import javax.persistence.JoinColumn; 15 import javax.persistence.ManyToOne; 16 import javax.persistence.OneToMany; 17 import javax.persistence.Table;
18 19 import org.hibernate.annotations.GenericGenerator; 20 21 /** 22 * @ClassName: Product 23 * @Description: TODO 24 * @author jed 25 * @date 2017年2月26日下午7:08:59 26 * 27 */ 28 @Entity 29 @Table(name="t_product") 30 public class Product { 31 32 private int id; 33 private
String name; //名字 34 private int price; //價格 35 private int stock; //存儲 36 private String proPic; //圖片 37 private String description; //描述 38 private int hot; //默認0不熱賣 0:不熱賣 ,1:熱賣 39 private Date hotTime; //熱賣時間 40 private int specialPrice; //特價0不打特價 0:不打熱價,1:打特價 41 private Date specialPriceTime; //特價時間 42 43 private ProductBigType bigType; //商品和商品大類是多對一關系 44 private ProductSmallType smallType; //商品和商品小類是多對一關系 45 private List<OrderProduct> orderProductList = new ArrayList<OrderProduct>(); //商品和訂單商品是一對多關系 46 47 @Id 48 @GeneratedValue(generator="_native") 49 @GenericGenerator(name="_native",strategy="native") 50 public int getId() { 51 return id; 52 } 53 public void setId(int id) { 54 this.id = id; 55 } 56 57 @Column(length=50) 58 public String getName() { 59 return name; 60 } 61 public void setName(String name) { 62 this.name = name; 63 } 64 public int getPrice() { 65 return price; 66 } 67 public void setPrice(int price) { 68 this.price = price; 69 } 70 public int getStock() { 71 return stock; 72 } 73 public void setStock(int stock) { 74 this.stock = stock; 75 } 76 public String getProPic() { 77 return proPic; 78 } 79 public void setProPic(String proPic) { 80 this.proPic = proPic; 81 } 82 @Column(length=2000) 83 public String getDescription() { 84 return description; 85 } 86 public void setDescription(String description) { 87 this.description = description; 88 } 89 public int getHot() { 90 return hot; 91 } 92 public void setHot(int hot) { 93 this.hot = hot; 94 } 95 public Date getHotTime() { 96 return hotTime; 97 } 98 public void setHotTime(Date hotTime) { 99 this.hotTime = hotTime; 100 } 101 public int getSpecialPrice() { 102 return specialPrice; 103 } 104 public void setSpecialPrice(int specialPrice) { 105 this.specialPrice = specialPrice; 106 } 107 public Date getSpecialPriceTime() { 108 return specialPriceTime; 109 } 110 public void setSpecialPriceTime(Date specialPriceTime) { 111 this.specialPriceTime = specialPriceTime; 112 } 113 114 @ManyToOne 115 @JoinColumn(name="bigTypeId") //外鍵關聯 116 public ProductBigType getBigType() { 117 return bigType; 118 } 119 public void setBigType(ProductBigType bigType) { 120 this.bigType = bigType; 121 } 122 123 @ManyToOne 124 @JoinColumn(name="smallTypeId") //外鍵關聯 125 public ProductSmallType getSmallType() { 126 return smallType; 127 } 128 public void setSmallType(ProductSmallType smallType) { 129 this.smallType = smallType; 130 } 131 132 @OneToMany 133 @JoinColumn(name="productId") 134 public List<OrderProduct> getOrderProductList() { 135 return orderProductList; 136 } 137 public void setOrderProductList(List<OrderProduct> orderProductList) { 138 this.orderProductList = orderProductList; 139 } 140 141 142 143 }
View Code

實體對象有Date類型字段,有list,還有級聯對象ProductBigType、ProductSmallType。

處理使用到jsonConfig,其中jsonConfig.setExcludes 方法去除不需要的屬性,前臺不展示。registerJsonValueProcessor 處理得到我們想要的字段值

技術分享
 1 /**
 2      * 
 3      * @MethodName: list
 4      * @Description: 獲取商品
 5      * @author jed
 6      * @date 2017年5月7日下午5:23:23
 7      * @param @return    
 8      * @return String    返回類型
 9      * @return
10      * @throws Exception 
11      *
12      */
13     public String list() throws Exception{
14         PageBean pageBean = new PageBean(Integer.parseInt(page), Integer.parseInt(rows));
15         List<Product> productList = productService.findProductList(productDetail, pageBean);
16         long total = productService.getProductCount(productDetail);
17         JsonConfig jsonConfig = new JsonConfig();
18         jsonConfig.setExcludes(new String[]{"orderProductList"}); //去除要排除的屬性   前臺不展示
19         jsonConfig.registerJsonValueProcessor(java.util.Date.class, new DateJsonValueProcessor("yyyy-MM-dd")); //日期處理
20         jsonConfig.registerJsonValueProcessor(ProductBigType.class, new ObjectJsonValueProcessor(new String[]{"id","name"}, ProductBigType.class));//商品大類的id和name
21         jsonConfig.registerJsonValueProcessor(ProductSmallType.class, new ObjectJsonValueProcessor(new String[]{"id","name"},ProductSmallType.class )); //商品小類的id和name
22         JSONArray rows = JSONArray.fromObject(productList, jsonConfig);
23         JSONObject result = new JSONObject();
24         result.put("rows", rows);
25         result.put("total", total);
26         ResponseUtil.write(ServletActionContext.getResponse(), result);
27         return null;
28     }
View Code

日期處理類:實現JsonValueProcessor

技術分享
 1 package com.hik.action;
 2 
 3 import java.text.SimpleDateFormat;
 4 
 5 import net.sf.json.JsonConfig;
 6 import net.sf.json.processors.JsonValueProcessor;
 7 
 8 /**
 9  * json-lib 日期處理類
10  * @author Administrator
11  *
12  */
13 public class DateJsonValueProcessor implements JsonValueProcessor{
14 
15     private String format;  
16     
17     public DateJsonValueProcessor(String format){  
18         this.format = format;  
19     }  
20     
21     public Object processArrayValue(Object value, JsonConfig jsonConfig) {
22         // TODO Auto-generated method stub
23         return null;
24     }
25 
26     public Object processObjectValue(String key, Object value, JsonConfig jsonConfig) {
27         if(value == null)  
28         {  
29             return "";  
30         }  
31         if(value instanceof java.sql.Timestamp)  
32         {  
33             String str = new SimpleDateFormat(format).format((java.sql.Timestamp)value);  
34             return str;  
35         }  
36         if (value instanceof java.util.Date)  
37         {  
38             String str = new SimpleDateFormat(format).format((java.util.Date) value);  
39             return str;  
40         }  
41           
42         return value.toString(); 
43     }
44 
45 }
View Code

對象級聯處理:實現JsonValueProcessor

技術分享
 1 package com.hik.action;
 2 
 3 import java.beans.PropertyDescriptor;
 4 import java.lang.reflect.Method;
 5 
 6 import net.sf.json.JSONObject;
 7 import net.sf.json.JsonConfig;
 8 import net.sf.json.processors.JsonValueProcessor;
 9 
10 /**
11  * 解決對象級聯問題
12  * @author Administrator
13  *
14  */
15 public class ObjectJsonValueProcessor implements JsonValueProcessor{
16 
17     /**
18      * 保留的字段
19      */
20     private String[] properties;  
21     
22     /**
23      * 處理類型
24      */
25     private Class<?> clazz;  
26     
27     /**
28      * 構造方法 
29      * @param properties
30      * @param clazz
31      */
32     public ObjectJsonValueProcessor(String[] properties,Class<?> clazz){  
33         this.properties = properties;  
34         this.clazz =clazz;  
35     }  
36     
37     public Object processArrayValue(Object arg0, JsonConfig arg1) {
38         // TODO Auto-generated method stub
39         return null;
40     }
41 
42     public Object processObjectValue(String key, Object value, JsonConfig jsonConfig) {
43         PropertyDescriptor pd = null;  
44         Method method = null;  
45         StringBuffer json = new StringBuffer("{");  
46         try{  
47             for(int i=0;i<properties.length;i++){  
48                 pd = new PropertyDescriptor(properties[i], clazz);  
49                 method = pd.getReadMethod();  
50                 String v = String.valueOf(method.invoke(value));  
51                 json.append("‘"+properties[i]+"‘:‘"+v+"‘");  
52                 json.append(i != properties.length-1?",":"");  
53             }  
54             json.append("}");  
55         }catch (Exception e) {  
56             e.printStackTrace();  
57         }  
58         return JSONObject.fromObject(json.toString());  
59     }
60 
61 }
View Code

jsonConfig處理日期及對象級聯問題