在javaweb开发中经常需要把java类和JSON数据进行转换
封装测试类
public class JsonUtil {
private static String DataFormat ="yyyy-MM-dd HH:mm:ss";
private static ObjectMapper objectMapper = new ObjectMapper();
static{
//对象所以字段
objectMapper.setSerializationInclusion(Include.ALWAYS);
//取消默认时间戳
objectMapper.configure(SerializationFeature.WRITE_DATE_KEYS_AS_TIMESTAMPS, false);
//取消空bean错误
objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS,false);
//统一日期格式
objectMapper.setDateFormat(new SimpleDateFormat(DataFormat));
//忽略json字符串没有对应java类型错误
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
}
public static <T>String obj2String(T object){
//java类转换JSON
if(object==null){
return null;
}
try {
if(object instanceof String){
//判断java类是否是字符串 并返回