- 一定注意自己的包是
import net.sf.json.JSONArray;
导入方法为在pom.xml 中添加依赖, 一定注意要添加这个jdk15
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>
- 含有Date类型的List 转成json,
imgseaModels是要转换成json的List
JsonConfig jsonConfig = new JsonConfig();
jsonConfig.registerJsonValueProcessor(Date.class, new JsonDateValueProcessor());
JSONArray jsonArray = JSONArray.fromObject(imgseaModels, jsonConfig);
- 新建一个JsonDateValueProcessor类
package cn.njust.label.main.utils;
import java.text.SimpleDateFormat;
import java.util.Date;
import net.sf.json.JsonConfig;
import net.sf.json.processors.JsonValueProcessor;
public class JsonDateValueProcessor implements JsonValueProcessor{
private String datePattern = "yyyy-MM-dd HH:mm:ss";//默认样式,可以在构造方法中修改
public JsonDateValueProcessor() {
super();
}
public JsonDateValueProcessor(String datePattern) {
super();
this.datePattern = datePattern;
}
public Object processArrayValue(Object value, JsonConfig jsonConfig) {
try {
if(value instanceof Date){
SimpleDateFormat sdf = new SimpleDateFormat(datePattern);
Date date = (Date)value;
return sdf.format(date);
}
return value == null ? null : value.toString();
} catch (Exception e) {
return null;
}
}
public Object processObjectValue(String key, Object value, JsonConfig jsonConfig) {
return processArrayValue(value, jsonConfig);
}
public String getDatePattern() {
return datePattern;
}
public void setDatePattern(String datePattern) {
this.datePattern = datePattern;
}
}
结果:
image.png
网友评论