java jackson json字符串、对象、json结构之间互相转换

public class JSONUtil {
/**
* json转对象
*
* @param json
* @param clazz<T>
* @return
*/
public final static <T> T parseObject(String json, Class<T> clazz) {
ObjectMapper mapper = new ObjectMapper();
try {
//忽略未知属性的反序列化
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
return mapper.readValue(json, clazz);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;
}
/**
* json转node
*
* @param json
* @return
*/
public final static <T> T toNode(String json) {
ObjectMapper mapper = new ObjectMapper();
try {
return (T) mapper.readTree(json);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;
}
/**
* 对象转json
*
* @param obj
* @return
*/
public final static String toJSONString(Object obj) {
ObjectMapper mapper = new ObjectMapper();
try {
return mapper.writeValueAsString(obj);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;
}
/*/**
* 对象转jsonNode
* @param Object
* @return jsonNode
*/
public final static <T> T objToJsonNode(Object obj) {
ObjectMapper mapper = new ObjectMapper();
try {
String s = mapper.writeValueAsString(obj);
return (T) mapper.readTree(s);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;
}
/**
* 转换
*
* @param obj
* @param clazz
* @param <T>
* @return
*/
public final static <T> T convertValue(Object obj, Class<T> clazz) {
ObjectMapper mapper = new ObjectMapper();
return mapper.convertValue(obj, clazz);
}
}
posted @   lambertlt  阅读(613)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
历史上的今天:
2021-07-14 ANN 学习
点击右上角即可分享
微信分享提示