代码如下:
package com.chuang.utils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import java.text.SimpleDateFormat;
/**
* JSON工具类:提供四个方法
* 1.字符串转换为对象
* 2.对象转换为JSON字符串
* 3.日期类型转化为固定的日期格式JSON字符串
* 4.日期类型转换为自定义的日期格式JSON字符串
* */
public class JSONUtils {
//提供JSON字符串转化为对象的功能
public static <T> T getObj(String json,Class<T> clazz){
//ObjectMapper mapper = new ObjectMapper();
try {
// return mapper.readValue(json,clazz);
return new ObjectMapper().readValue(json,clazz);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;
}
//提供对象转化为JSON字符串的功能
public static String getJson(Object o){
//ObjectMapper mapper = new ObjectMapper();
try {
//return mapper.writeValueAsString(o);
return new ObjectMapper().writeValueAsString(o);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;
}
//重载-提供固定格式的日期转换为JSON字符串格式
public static String getJsonDateFormate(Object o){
return getJsonDateFormate(o,"yyyy-MM-dd HH:mm:ss");
}
//提供自定义格式的日期转换为JSON字符串格式
public static String getJsonDateFormate(Object o,String dateFormat){
// ObjectMapper mapper = new ObjectMapper();
// SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormat);
// ObjectMapper configure = mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
// mapper.setDateFormat(simpleDateFormat);
try {
//return mapper.writeValueAsString(o);
//链式编程
return new ObjectMapper().configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,false)
.setDateFormat(new SimpleDateFormat(dateFormat))
.writeValueAsString(o);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;
}
}