当前位置: 代码迷 >> 综合 >> jackson 封装JsonUtil 工具类
  详细解决方案

jackson 封装JsonUtil 工具类

热度:62   发布时间:2023-10-17 16:59:19.0

为什么用jackson,而不是用fastjson和 gson

fastjson:性能最好,不过代码质量低,经常爆出bug

gson:谷歌出品,代码质量好,性能一般,

而jackson性能只比fastjson 差一点,代码质量好,也是springboot 默认的json工具

 

引入依赖

gradle

compile "com.fasterxml.jackson.core:jackson-databind:2.11.2“

maven

<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>2.11.2</version>
</dependency>

 

代码

/*** @author chenye* 操作json的封装方法* https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind* dependency "com.fasterxml.jackson.core:jackson-databind:2.11.2“* @date 2020-0828*/
public class JsonUtil {/*** json转换成对象*/public static <T> T toObject(Class classz, String jsonString) {ObjectMapper mapper = new ObjectMapper();try {return (T) mapper.readValue(jsonString, classz);} catch (JsonProcessingException e) {System.out.println(jsonString + "转化失败");e.printStackTrace();}return null;}/*** 对象转换成json*/public static String toJsonString(Object object) {ObjectMapper mapper = new ObjectMapper();try {return mapper.writeValueAsString(object);} catch (JsonProcessingException e) {System.out.println(object + "转化失败");e.printStackTrace();}return null;}
}
  相关解决方案