将java.util.Date类型转换成json时,使用JsonValueProcessor将date转换成希望的类型

问题描述:

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 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;
}

}

上一篇:Java 从 Redis中取出的Json字符串 带斜杠的问题解决方案


下一篇:附006.harbor.cfg配置文件详解