一、maven依赖引入jackson

		<dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.12.5</version>
        </dependency>

在这里插入图片描述
jackson-databind依赖见下:

    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-annotations</artifactId>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
    </dependency>

二、JsonUtil工具类

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonUtil {
    public static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    /**
     * Json encode
     *
     * @param object object
     * @return String
     */
    public static String encode(Object object) {
        try {
            return OBJECT_MAPPER.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("Json encode failed!", e);
        }
    }

    /**
     * Json decode
     *
     * @param json          json
     * @param typeReference typeReference
     * @param <T>           T
     * @return T
     */
    public static <T> T decode(String json, TypeReference<T> typeReference) {
        try {
            return OBJECT_MAPPER.readValue(json, typeReference);
        } catch (Exception e) {
            throw new RuntimeException("Json decode failed!", e);
        }
    }

    /**
     * Json decode
     *
     * @param json        json
     * @param targetClass targetClass
     * @param <T>         T
     * @return T
     */
    public static <T> T decode(String json, Class<T> targetClass) {
        try {
            return OBJECT_MAPPER.readValue(json, targetClass);
        } catch (Exception e) {
            throw new RuntimeException("Json decode failed!", e);
        }
    }
}

三、使用示例

定义一个User对象

    @AllArgsConstructor
    @NoArgsConstructor
    @Data
    public static class User {
        private String name;
        private Integer age;
    }
  • encode() 单个对象
String str = JsonUtil.encode(new User("张三", 10));

// {"name":"张三","age":10}
System.out.println(str);
  • encode() 对象集合
   List<User> userList  = Lists.newArrayList();
   userList.add(new User("张三", 10));
   userList.add(new User("李四", 12));
       
   String str = JsonUtil.encode(userList);
   
   // [{"name":"张三","age":10},{"name":"李四","age":12}]
   System.out.println(str);    
  • decode() 单个对象
   String json = "{\"name\":\"stelin\",\"age\":18}";
   User user = JsonUtil.decode(json, User.class);
   
   // JsonUtil.User(name=stelin, age=18)
   System.out.println(user);
  • decode() 对象集合
String str = "[{\"name\":\"张三\",\"age\":10},{\"name\":\"李四\",\"age\":12}]";

List<User> userList = JsonUtil.decode(str, new TypeReference<List<User>>() {
        });
        
// [JsonUtil.User(name=张三, age=10), JsonUtil.User(name=李四, age=12)]
System.out.println(userList);
  • decode() 字符串集合
String str = "[1, 2, 3]";

List<String> list = JsonUtil.decode(str, new TypeReference<List<String>>() {
});

// [1, 2, 3]
System.out.println(list);

很多jar包都会有类TypeReference,别错误地引用了,注意这里的TypeReference是com.fasterxml.jackson.core.type.TypeReference。

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐