对象转为JSON/JSON转为对象
我们可以使用spring中提供的工具类
只要项目中有spring-boot-starter-web jar包就可以

ObjectMapper类


- readValue方法可以将JSON转换为对象
readValue(JsonParser,Class)方法
参数:
jsonParser 你要转换的JSON数据
Class 你要将JSON转换的目标类型,接收的是类的Class对象


- writeValueAsString方法可以将对象转换为JSON
writeValueAsString(Object)方法
参数:
Object 传入一个需要转换JSON格式的对象

在这里我写了一个ObjectMapperUtil 工具类,提供了JSON转对象、对象转JSON的方法
/**
* 对象转换成JSON
* JSON转换成对象
* @author Jason_liu
* 2020年6月5日
*/
public class ObjectMapperUtil {
public static final ObjectMapper OM=new ObjectMapper();
//将对象转化为JSON
public static String toJSON(Object target) {
try {
//通过对象--JSON
return OM.writeValueAsString(target);
} catch (JsonProcessingException e) {
//检查异常转化成运行异常
e.printStackTrace();
throw new RuntimeException(e);
}
}
//将JsoN转化成对象
public static <T> T toObject(String json,Class<T> cls){
try {
return OM.readValue(json, cls);
} catch (JsonProcessingException e) {
e.printStackTrace();
throw new RuntimeException();
}
}
}
本文介绍如何在SpringBoot项目中使用ObjectMapper类实现JSON与对象之间的相互转换,包括readValue和writeValueAsString方法的使用,以及自定义工具类ObjectMapperUtil的实现。
114

被折叠的 条评论
为什么被折叠?



