注意先导jackson包
package com.yenyue.util;
import java.text.SimpleDateFormat;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
/**
* @ClassName: JsonUtils
* @author: YanYue
* @date: 2021/5/26
* @Description:
*/
public class JsonUtils {
private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private static ObjectMapper mapper = new ObjectMapper();
static {
//关闭时间戳功能
mapper.configure(SerializationFeature.WRITE_DATE_KEYS_AS_TIMESTAMPS,false);
}
public static String getJson(Object o){
try {
mapper.setDateFormat(simpleDateFormat);
return mapper.writeValueAsString(o);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;
}
public static String getJson(Object o,String format){
try {
SimpleDateFormat sim = new SimpleDateFormat(format);
mapper.setDateFormat(sim);
return mapper.writeValueAsString(o);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;
}
}
调用
List<Student> list = new ArrayList();
list.add(new Student("张三",22));
list.add(new Student("李四",23));
String s = JsonUtils.getJson(list);
System.out.println(s);
自定义日期格式
list.add(new Date());
System.out.println(JsonUtils.getJson(list,"yyyy-MM-dd"));