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