1.JSON日期格式转换
默认JSON对DATE类型会转换成一个多属性对象, 而不是单独的一个字符串, 在某些应用处理上不是很方便, 可以利用JsonValueProcessor来实现日期的转换.
默认格式:
"lastUpdate": {
"date": 29,
"day": 3,
"hours": 14,
"minutes": 46,
"month": 1,
"seconds": 41,
"time": 1330498001000,
"timezoneOffset": -480,
"year": 112
},
转换后格式:
"lastUpdate": "2012-02-29 14:46:41"
自定义一个日期处理器:
DateJsonValueProcessor是实现了一个JsonValueProcessor接口(两种方式)
- importjava.text.SimpleDateFormat;
- importjava.util.Date;
-
- importnet.sf.json.JsonConfig;
- importnet.sf.json.processors.JsonValueProcessor;
-
-
-
-
-
- publicclassDateJsonValueProcessorimplementsJsonValueProcessor
- {
- privateStringformat="yyyy-MM-ddHH:mm:ss";
-
- publicDateJsonValueProcessor()
- {
-
- }
-
- publicDateJsonValueProcessor(Stringformat)
- {
-
- this.format=format;
- }
-
- publicObjectprocessArrayValue(Objectvalue,JsonConfigjsonConfig)
- {
-
- String[]obj={};
- if(valueinstanceofDate[])
- {
- SimpleDateFormatsf=newSimpleDateFormat(format);
- Date[]dates=(Date[])value;
- obj=newString[dates.length];
- for(inti=0;i<dates.length;i++)
- {
- obj[i]=sf.format(dates[i]);
- }
- }
- returnobj;
- }
-
- publicObjectprocessObjectValue(Stringkey,Objectvalue,JsonConfigjsonConfig)
- {
-
- if(valueinstanceofDate)
- {
- Stringstr=newSimpleDateFormat(format).format((Date)value);
- returnstr;
- }
- returnvalue;
- }
-
- publicStringgetFormat()
- {
-
- returnformat;
- }
-
- publicvoidsetFormat(Stringformat)
- {
-
- this.format=format;
- }
-
- }
或:
- packageorg.ymm.util;
-
- importjava.text.SimpleDateFormat;
- importnet.sf.json.JsonConfig;
- importnet.sf.json.processors.JsonValueProcessor;
-
- publicclassDateJsonValueProcessorimplementsJsonValueProcessor
- {
-
- privateStringformat;
- publicDateJsonValueProcessor(Stringformat){
- this.format=format;
- }
-
- publicObjectprocessArrayValue(Objectvalue,JsonConfigjsonConfig)
- {
- returnnull;
- }
-
- publicObjectprocessObjectValue(Stringkey,Objectvalue,JsonConfigjsonConfig)
- {
- if(value==null)
- {
- return"";
- }
- if(valueinstanceofjava.sql.Timestamp)
- {
- Stringstr=newSimpleDateFormat(format).format((java.sql.Timestamp)value);
- returnstr;
- }
- if(valueinstanceofjava.util.Date)
- {
- Stringstr=newSimpleDateFormat(format).format((java.util.Date)value);
- returnstr;
- }
-
- returnvalue.toString();
- }
- }
-
转换调用代码:
public String queryEmpAll() throws IOException{
System.out.println("queryEmpAll!!!!!!!!!!!!!!!!!!!!!!!");
// PrintWriter out=ServletActionContext.getResponse().getWriter();
JsonConfig jsonConfig = new JsonConfig();
jsonConfig.registerJsonValueProcessor(java.util.Date.class, new JsonDateValueProcessor());
jsonConfig.registerJsonValueProcessor(java.sql.Timestamp.class, new JsonDateValueProcessor());
Map map=new HashMap();
map.put("total", 3);
map.put("data", ies.getAll());
JSONObject jn=JSONObject.fromObject(map,jsonConfig);
System.out.println(jn.toString());
// out.print(jn.toString());
return null;
}