package com.jt.util;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
/*
*功能:JSON与对象的相互转化
* 1.对象转json
* 2.json转对象
*/
public class ObjectMapperUtil {
private static final ObjectMapper MAPPER = new ObjectMapper();
//1.对象转json
public static String toJSON(Object object){ //工具类一般设置为静态static
try {
return MAPPER.writeValueAsString(object); //转换为json 并返回
} catch (JsonProcessingException e) {
e.printStackTrace();
throw new RuntimeException(e); //返回异常类型
}
}
//2.json转对象,用户传递什么类型就返回什么类型
public static <T> T toObj(String json,Class<T> target){
try {
return MAPPER.readValue(json, target);
} catch (JsonProcessingException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
JSON与对象的相互转化API(纯代码)
最新推荐文章于 2021-11-16 09:05:45 发布