一:List 转json
List<User> list = new ArrayList<>();
JsonConfig jsonConfig = new JsonConfig();
jsonConfig.registerJsonValueProcessor(Date.class,
new JsonDateValueProcessor());// 注入处理Date类
JSONArray json = JSONArray.fromObject(list,jsonConfig);
String str = json.toString();
处理时间类
public class JsonDateValueProcessor implements JsonValueProcessor {
@Override
public Object processArrayValue(Object o, JsonConfig jsonConfig) {
return process(o);
}
@Override
public Object processObjectValue(String s, Object o, JsonConfig jsonConfig) {
return process(o);
}
private Object process(Object obj) {
if (obj == null) {// 如果时间为null,则返回空字串
return "";
}
if (obj instanceof Date) {
obj = new java.util.Date(((Date) obj).getTime());
}
if (obj instanceof java.util.Date) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",Locale.UK);// 格式化时间为yyyy-MM-dd类型
return sdf.format(obj);
} else {
return new Object();
}
}
}
二:String转List
List<User> list = new ArrayList<>();
ObjectMapper mapper = new ObjectMapper();
JavaType jt = mapper.getTypeFactory().constructParametricType(ArrayList.class, User);
List<User> list = (List<User>) mapper.readValue(String , jt);
三:依赖
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<classifier>jdk15</classifier>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>