jsonConfig处理日期及对象级联问题
Posted 心和梦的方向
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了jsonConfig处理日期及对象级联问题相关的知识,希望对你有一定的参考价值。
项目中经常用到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 }
实体对象有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 }
日期处理类:实现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 }
对象级联处理:实现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 }
以上是关于jsonConfig处理日期及对象级联问题的主要内容,如果未能解决你的问题,请参考以下文章
Java中 jsonArray和Java List对象互转,日期处理