import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* 对象与JSON之间的互转
*/
public class JsonUtils {
//转换JSOn的对象
private static ObjectMapper om = new ObjectMapper();
static{
om.setSerializationInclusion(Include.NON_NULL);
}
//对象转JSON格式字符串
public static String getObjectToJson(Object obj){
try {
return om.writeValueAsString(obj);
} catch (JsonProcessingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
//JSON格式的字符串转成对象
public static <T> T getJsonToObject(String json, Class<T> beanType){
T t = null;
try {
t = om.readValue(json, beanType);
} catch (Exception e) {
// TODO: handle exception
}
return t;
}
}
对象与JSON之间的互转
最新推荐文章于 2021-12-19 19:33:52 发布