Jackson解析JSON

hotCode / 2023-08-15 / 原文

Jackson有三个核心包,分别是 Streaming、Databind、Annotations,通过这些包可以方便的对 JSON 进行操作
1.Streaming: 在jackson-core 模块。定义了一些流处理相关的 API 以及特定的 JSON 实现
2.Annotations: 在 jackson-annotations 模块,包含了 Jackson 中的注解
3.Databind: 在 jackson-databind 模块, 在Streaming 包的基础上实现了数据绑定,依赖于 Streaming 和 Annotations 包

ObjectMapper 对象映射器: 进行Java对象和 JSON 字符串之间快速转换
1.readValue() 方法可以进行 JSON 的反序列化操作,比如可以将字符串、文件流、字节流、字节数组等将常见的内容转换成 Java 对象
2.writeValue() 方法可以进行 JSON 的序列化操作,可以将 Java 对象转换成 JSON 字符串

1.字符串转换成对象(POJO): User user = objectMapper.readValue(str, User.class);
2.字符串转换成对象(POJO)作为泛型: ResultDTO data = objectMapper.readValue(dtoSerializationResult, new TypeReference<ResultDTO>() {});
3.字符串转换成List: JavaType javaType = objectMapper.getTypeFactory().constructParametricType(List.class, User.class);
List userList = objectMapper.readValue(jsonStr, javaType);
4.字符串转换成Map: Map<String, Object> employeeMap = objectMapper.readValue(expectedJson, new TypeReference() {});

JavaType
Map类型: mapper.getTypeFactory().constructParametricType(Map.class,String.class,Student.class);
第二个参数是Map的key,第三个参数是Map的value
List类型: personList = mapper.readValue(mapper.writeValueAsString(personList),mapper.getTypeFactory().constructParametricType(List.class,Person.class));

`public class JacksonTest2 {

private static ObjectMapper objectMapper = new ObjectMapper();

//序列化 Java对象转化为JSON
@Test
public void poJoToJsonString() throws JsonProcessingException {
    User user = new User();
    user.setId(1L);
    user.setName("ljc");
    user.setPwd("123");
    user.setAddr("内蒙古");
    user.setWebsiteUrl("http:www.baidu.com");
    user.setRegisterDate(new Date());
    user.setBirthDay(LocalDateTime.now());
    user.setSkillList(Arrays.asList("Java", "C++"));
    System.out.println(user.toString());
    String string = objectMapper.writeValueAsString(user);
    System.out.println(string);

}

// 反序列化 字符串转化为对象
@Test
public void jsonStringToPoJo() throws JsonProcessingException {
    String str = "{\"id\":1,\"name\":\"ljc\",\"pwd\":\"123\",\"addr\":\"内蒙古\",\"websiteUrl\":\"http:www.baidu.com\",\"registerDate\":\"2022-04-18 10:59:44\",\"birthDay\":\"2022-04-18 10:59:44\"}";
    User user = objectMapper.readValue(str, User.class);
    System.out.println(user);
}

// ResultDTO<T>
@Test
public void jsonStringToDTO() throws JsonProcessingException {
    User user = new User();
    user.setName("ljc");
    user.setWebsiteUrl("http:www.baidu.com");
    ResultDTO<User> userResultDTO = ResultDTO.buildSuccess(user);
    String dtoSerializationResult = objectMapper.writeValueAsString(userResultDTO);
    System.out.println("dtoSerializationResult:" + dtoSerializationResult);
    // 反序列化为ResultDTO<User>
    ResultDTO<User> data = objectMapper.readValue(dtoSerializationResult, new TypeReference<ResultDTO<User>>() {
    });
    System.out.println("data:"+data);
    System.out.println("user:"+data.getData());
}

// List
@Test
public void jsonStringToList() throws JsonProcessingException {
    String jsonStr = "["+
            "{\"id\":1,\"name\":\"ljc\",\"pwd\":\"123\",\"addr\":\"内蒙古\",\"websiteUrl\":\"http:www.baidu.com\"}" +
            ",{\"id\":2,\"name\":\"qsy\",\"pwd\":\"123\",\"addr\":\"吉林\",\"websiteUrl\":\"http:www.baidu.com\"}" +
             "]";
    // TypeReference<List<User>> typeReference = new TypeReference<List<User>>() {};
    List<User> personList = objectMapper.readValue(jsonStr, new TypeReference<List<User>>() {});
    for (User person : personList) {
        System.out.println(person);
    }

    // 第2种写法
    JavaType javaType = objectMapper.getTypeFactory().constructParametricType(List.class, User.class);
    List<User> userList = objectMapper.readValue(jsonStr, javaType);
    for (User person : userList) {
        System.out.println(person);
    }

}


@Test
public void jsonStringToMap() throws IOException {
    String expectedJson = "{\"name\":\"aLang\",\"age\":27,\"skillList\":[\"java\",\"c++\"]}";
    Map<String, Object> employeeMap = objectMapper.readValue(expectedJson, new TypeReference<Map>() {});
    System.out.println(employeeMap.getClass());
    for (Map.Entry<String, Object> entry : employeeMap.entrySet()) {
        System.out.println(entry.getKey() + ":" + entry.getValue());
    }
}

}`