先写个帮助类
public class JsonValueProcessorImpl implements JsonValueProcessor {
private String format = "yyyy-MM-dd";
public JsonValueProcessorImpl() {
super();
}
public JsonValueProcessorImpl(String format) {
super();
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 java.util.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 JsonValueProcessorImpl());
json=JSONArray.fromObject(types,jsonConfig).toString();
本文介绍了一个用于处理JSON中日期格式的Java帮助类实现。通过自定义JsonValueProcessorImpl类,可以将日期对象转换为指定格式的字符串,支持数组和单个日期对象的处理。
2585

被折叠的 条评论
为什么被折叠?



