问题描述:
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形式
解决方案:
JsonConfig jsonConfig = new JsonConfig();
jsonConfig.registerJsonValueProcessor(java.util.Date.class, new DateJsonValueProcessor("yyyy-MM-dd HH:mm:ss"));
JSONObject jsonObj = JSONObject.fromObject(map, jsonConfig);
class DateJsonValueProcessor implements JsonValueProcessor {
private String format = "yyyy-MM-dd";
public DateJsonValueProcessor() {
}
public DateJsonValueProcessor(String format) {
this.format = format;
}
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;
}
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;
}
}