带日期的bean转为json(bean->JSON)
原文链接:http://blog.sina.com.cn/s/blog_5f1fe33f0100jibg.html
示例代码:
JsonBean bean = new JsonBean();
bean.setName("NewBaby");
bean.setAge(1);
bean.setBorn(new Date());
jo = JSONObject.fromObject(bean);
System.out.println("bean->json:" +
jo.toString());
打印结果:bean->json:{"age":1,"born":{"date":10,"day":3,"hours":14,"minutes":14,"month":2,"seconds":1,"time":1268201641228,"timezoneOffset":-480,"year":110},"name":"NewBaby"}
这时你会发现它把bean对象里的util.Date这个类型的所有属性一一转换出来。在实际运用过程中,大多数情况下我们希望能转化为yyyy-MM-dd这种格式,下面就讲一讲如何实现。
首先要写一个新的类JsonDateValueProcessor如下:
public class JsonDateValueProcessor implements JsonValueProcessor {
private String datePattern = "yyyy-MM-dd";
public JsonDateValueProcessor() {
super();
}
public JsonDateValueProcessor(String format) {
super();
this.datePattern = format;
}
public Object processArrayValue(Object value, JsonConfig jsonConfig) {
return process(value);
}
public Object processObjectValue(String key, Object value,
JsonConfig jsonConfig) {
return process(value);
}
private Object process(Object value) {
try {
if (value instanceof Date) {
SimpleDateFormat sdf = new SimpleDateFormat(datePattern,
Locale.UK);
return sdf.format((Date) value);
}
return value == null ? "" : value.toString();
} catch (Exception e) {
return "";
}
}
public String getDatePattern() {
return datePattern;
}
public void setDatePattern(String pDatePattern) {
datePattern = pDatePattern;
}
}
测试代码:
JsonBean bean = new JsonBean();
bean.setName("NewBaby");
bean.setAge(1);
bean.setBorn(new Date());
JsonConfig jsonConfig = new JsonConfig();
jsonConfig.registerJsonValueProcessor(Date.class,new JsonDateValueProcessor());
JSONObject jo = JSONObject.fromObject(bean, jsonConfig);
System.out.println("bean->json:" + jo.toString());
打印结果:bean->json:{"age":1,"born":"2010-03-10","name":"NewBaby"}
这就能得到我们想要的结果了。