原文:https://blog.csdn.net/u013628196/article/details/55518075
java里面时间类型转换成json数据就成这样了:
"createTime":{"date":30,"day":3,"hours":15,"minutes":14,"month":3,"nanos":0,"seconds":38,"time":1209539678000,"timezoneOffset":-480,"year":108}
期望的结果:
将date转化成yyyy-MM-dd HH:mm:ss形式
下面开始操作
maven导入的包:
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>
新建DateJsonValueProcessor 类
import net.sf.json.JsonConfig;
import net.sf.json.processors.JsonValueProcessor;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateJsonValueProcessor implements JsonValueProcessor {
private String format = "yyyy-MM-dd HH:mm:ss";
public DateJsonValueProcessor() {
}
public DateJsonValueProcessor(String format) {
this.format = format;
}
@Override
public Object processArrayValue(Object value, JsonConfig jsonConfig) {
String[] obj = {};
if (value instanceof Date[]) {
SimpleDateFormat sf = new SimpleDateFormat(format);
Date[] dates = (Date[]) value;
obj = new String[dates.length];
for (int i = 0; i < dates.length; i++) {
obj[i] = sf.format(dates[i]);
}
}
return obj;
}
@Override
public Object processObjectValue(String key, Object value, JsonConfig jsonConfig) {
if (value instanceof Date) {
String str = new SimpleDateFormat(format).format((Date) value);
return str;
}
return value.toString();
}
public String getFormat() {
return format;
}
public void setFormat(String format) {
this.format = format;
}
}
使用方法:
JsonConfig jsonConfig = new JsonConfig();
jsonConfig.registerJsonValueProcessor(java.util.Date.class, new DateJsonValueProcessor("yyyy-MM-dd HH:mm:ss"));
JSONArray jarray = JSONArray.fromObject(list,jsonConfig);
temp = jarray.toString();
注意事项:
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
结果:
"createTime":"2017-02-17 13:59:18"