日期:2014-05-16 浏览次数:20282 次
1. Json-lib可以将Java对象很方便的转成json格式的字符串,使用教程(http://json-lib.sourceforge.net/usage.html)
但是当Java对象中有时间类型的时候。 Json-lib会把时间字段转换成:
{"date":17,"day":3,"hours":0,"minutes":0,"month":11,"nanos":0,"seconds":0,"time":345830400000,"timezoneOffset":-480,"year":80},"ENAME":"SMITH"}
如何处理呢?
第一种(extjs中处理的):http://blog.csdn.net/without0815/article/details/7788582
第二种(主要):
List list=iEmpDao.getListEmp(pageIndex, pageNo); //Map<String,Object> map = (Map<String,Object>)list.get(0); //JSONArray ja1=new JSONArray().fromObject(list); JSONArray ja = new JSONArray(); JsonConfig jf = new JsonConfig(); //jf.registerJsonValueProcessor(java.sql.Timestamp.class, new DateJsonValueProcessor("yyyy-MM-dd HH:mm:ss")); jf.registerJsonValueProcessor(java.sql.Timestamp.class, new DateJsonValueProcessor("yyyy-MM-dd")); jf.registerJsonValueProcessor(java.util.Date.class, new DateJsonValueProcessor("yyyy-MM-dd")); System.out.println(ja.fromObject(list,jf).toString()); return ja.fromObject(list,jf).toString();
DateJsonValueProcessor是实现了一个JsonValueProcessor接口
package org.ymm.util; import java.text.SimpleDateFormat; import net.sf.json.JsonConfig; import net.sf.json.processors.JsonValueProcessor; public class DateJsonValueProcessor implements JsonValueProcessor { private String format; public DateJsonValueProcessor(String format){ this.format = format; } public Object processArrayValue(Object value, JsonConfig jsonConfig) { 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(); } }只要是时间类型被处理格式化