Jackson常用功能演示

新建Maven工程

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>JacksonDemo</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.13.3</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.24</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.36</version>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.2.11</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
        </dependency>
    </dependencies>
</project>

ObjectMapper

@Slf4j
public class JacksonTest {

    /**
     * JavaBean转JSON字符串
     */
    @Test
    public void testJavaBeanToJson() {
        WeChat weChat = new WeChat();
        weChat.setId("zhuan2quan");
        weChat.setName("程序新视界");
        weChat.setInterest(new String[]{"Java", "Spring Boot", "JVM"});

        ObjectMapper mapper = new ObjectMapper();
        try {
            String result = mapper.writeValueAsString(weChat);
            System.out.println(result);
        } catch (JsonProcessingException e) {
            log.error("转换异常", e);
        }
    }

    /**
     * JSON字符串转JavaBean
     */
    @Test
    public void testJsonToJavaBean() {
        String json = "{\"id\":\"zhuan2quan\",\"name\":\"程序新视界\",\"interest\":[\"Java\",\"Spring Boot\",\"JVM\"]}";
        ObjectMapper mapper = new ObjectMapper();
        try {
            WeChat weChat = mapper.readValue(json, WeChat.class);
            System.out.println(weChat);
        } catch (JsonProcessingException e) {
            log.error("解析异常", e);
        }
    }

    /**
     * JSON字符串转Map集合
     */
    @Test
    public void testJsonToMap() {
        String json = "{\"id\":\"zhuan2quan\",\"name\":\"程序新视界\",\"interest\":[\"Java\",\"Spring Boot\",\"JVM\"]}";
        ObjectMapper mapper = new ObjectMapper();
        try {
            // 对泛型的反序列化,使用TypeReference可以明确的指定反序列化的类型。
            Map<String, Object> map = mapper.readValue(json, new TypeReference<Map<String, Object>>() {
            });
            System.out.println(map);
        } catch (JsonProcessingException e) {
            log.error("解析异常", e);
        }
    }

    /**
     * JavaBean转文件
     */
    @Test
    public void testJavaBeanToFile() {
        WeChat weChat = new WeChat();
        weChat.setId("zhuan2quan");
        weChat.setName("程序新视界");
        weChat.setInterest(new String[]{"Java", "Spring Boot", "JVM"});

        ObjectMapper mapper = new ObjectMapper();
        try {
            //写到文件
            mapper.writeValue(new File("json.txt"), weChat);

            //从文件中读取
            WeChat weChat1 = mapper.readValue(new File("json.txt"), WeChat.class);
            System.out.println(weChat1);
        } catch (IOException e) {
            log.error("转换异常", e);
        }
    }

    /**
     * JavaBean转字节流
     */
    @Test
    public void testJavaBeanToBytes() {
        WeChat weChat = new WeChat();
        weChat.setId("zhuan2quan");
        weChat.setName("程序新视界");
        weChat.setInterest(new String[]{"Java", "Spring Boot", "JVM"});

        ObjectMapper mapper = new ObjectMapper();
        try {
            // 写为字节流
            byte[] bytes = mapper.writeValueAsBytes(weChat);
            // 从字节流读取
            WeChat weChat1 = mapper.readValue(bytes, WeChat.class);
            System.out.println(weChat1);
        } catch (IOException e) {
            log.error("转换异常", e);
        }
    }
}

JsonNode

@Slf4j
public class JacksonNodeTest {
    /**
     * JavaBean转JSON字符串
     */
    @Test
    public void testJsonNode() {

        // 构建JSON树
        ObjectMapper mapper = new ObjectMapper();
        ObjectNode root = mapper.createObjectNode();
        root.put("id", "zhuan2quan");
        root.put("name", "程序新视界");
        ArrayNode interest = root.putArray("interest");
        interest.add("Java");
        interest.add("Spring Boot");
        interest.add("JVM");

        // JSON树转JSON字符串
        String json = null;
        try {
            json = mapper.writeValueAsString(root);
        } catch (JsonProcessingException e) {
            log.error("Json Node转换异常", e);
        }
        System.out.println(json);
    }

    /**
     * 解析JSON字符串为JSON树模型
     */
    @Test
    public void testJsonToJsonNode() {
        String json = "{\"id\":\"zhuan2quan\",\"name\":\"程序新视界\",\"interest\":[\"Java\",\"Spring Boot\",\"JVM\"]}";
        ObjectMapper mapper = new ObjectMapper();
        try {
            // 将JSON字符串转为JSON树
            JsonNode jsonNode = mapper.readTree(json);
            String name = jsonNode.path("name").asText();
            System.out.println(name);

            // 其中get方法和path功能相似,
            // 区别在于如果要读取的key在Json串中不存在时,get方法会null,
            // 而path会返回MissingNode实例对象,在链路方法情况下保证不会抛出异常。
            JsonNode interestNode = jsonNode.get("interest");
            if (interestNode.isArray()){
                for (JsonNode node : interestNode){
                    System.out.println(node.asText());
                }
            }
        } catch (JsonProcessingException e) {
            log.error("Json Node转换异常", e);
        }
    }
}

参考知乎:放弃FastJson!一篇就够,Jackson的功能原来如此之牛(万字干货) - 程序新视界的文章 - 知乎
https://zhuanlan.zhihu.com/p/352485162

posted @ 2022-08-28 21:32  xl4ng  阅读(23)  评论(0编辑  收藏  举报