JSON日期格式转换的时候,默认情况下JSON对date类型会转换成一个多属性对象,如:
“createTime”:{
“date”:11,
“day”:2,
“hours”:16,
“minutes”:15,
“month”:9,
“seconds”:12,
“time”:1665476112000,
“timezoneOffset”:-480,
“year”:122
}
这种格式我们用起来不是很方便, 可以利用JsonValueProcessor来实现日期的转换。
DateJsonValueProcessor类:
package com.winsun.utils;
import java.text.SimpleDateFormat;
import java.util.Date;
import net.sf.json.JsonConfig;
import net.sf.json.processors.JsonValueProcessor;
/**
* JSON日期格式转换
*
*/
public class DateJsonValueProcessor implements JsonValueProcessor {
private String format = "yyyy-MM-dd HH:mm:ss";
@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;
}
}
转换的时候调用:
JsonConfig jsonConfig = new JsonConfig();
(, new DateJsonValueProcessor());
//bean:我们要转换的实体类
JSONObject jsonObject = (bean, jsonConfig);
(());
预期结果:
“createTime”:“2022-10-11 16:15:12”