jackson-4

第五十一章 Jackson库之四 (解析和生成YAML文档)

在前面的章节中我们介绍了Jackson库解析和生成JSONXML文档的使用方法。在本章中,我们继续介绍如何使用Jackson库解析和生成YAML文档。因为Jackson对象映射(Object Mapping)的方法使用非常方便,所以,我们本章重点介绍这种方法。

如果使用Maven管理项目,需要将如下依赖关系加入项目的pom.xml文件中。Jackson Yaml代码库依赖于snakeyaml代码库。

<dependency>
    <groupId>org.yaml</groupId>
    <artifactId>snakeyaml</artifactId>
    <version>1.27</version>
</dependency>
<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-core</artifactId>
  <version>2.11.1</version>
</dependency>
<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-databind</artifactId>
  <version>2.11.1</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-annotations</artifactId>
    <version>2.11.1</version>
</dependency>
<dependency>
  <groupId>com.fasterxml.jackson.dataformat</groupId>
  <artifactId>jackson-dataformat-yaml</artifactId>
  <version>2.11.1</version>
</dependency>

如果使用Gradle管理项目,需要将如下依赖加入项目的build.gradle文件中。

repositories {
  mavenCentral()
}

dependencies {
  implementation 'org.yaml:snakeyaml:1.27'
  implementation 'com.fasterxml.jackson.core:jackson-core:2.11.1'
  implementation 'com.fasterxml.jackson.core:jackson-databind:2.11.1'
  implementation 'com.fasterxml.jackson.core:jackson-annotations:2.11.1'
  implementation 'com.fasterxml.jackson.dataformat:jackson-dataformat-yaml:2.11.1'
}

1 YAML文档生成

1.1 基本使用方法

YAML文档生成的方法与生成JSON、XML文档非常相似。在解析和生成YAML时,我们需要使用YAMLMapper类。YAMLMapper类继承自ObjectMapper类,所以,在解析和生成YAML时使用的函数接口是一致的。

例如,我们计划生成如下的YAML字符串。根节点包含name和age两个节点。

---
name: "David"
age: 22

为了生成上述的YAML文档,我们可以创建一个Person类。Person类中包含name和age两个成员变量。在main()函数中,我们在创建了新的YAMLMapper对象和Person对象之后,调用writeValueAsString()方法将Person对象转换为对应的YAML文档。

import java.io.IOException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLMapper;

public class Person {
    private String name = null;
    private Integer age = null;

    public Person(String name, Integer age) {
        this.name = name;
        this.age = age;
    }

    // Getters and Setters
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }

    public static void main(String[] args) {
        try {
            ObjectMapper mapper = new YAMLMapper();
            Person person = new Person("David", 22);

            // 生成YAML字符串
            System.out.println(mapper.writeValueAsString(person));
        } catch (IOException ex) {
            System.out.println(ex.getMessage());
        }
    }
}

上述的程序输出为:

---
name: "David"
age: 22

1.2 多级YAML文档生成

Jackson库也可以生成多级YAML文档。例如,在如下的YAML文档中,根节点包含department节点;Department节点包含name和code节点。

---
name: "David"
age: 22
department:
  name: "Computer Science"
  code: "CS"

为了生成上述的YAML文档,我们可以在Person类中添加一个Department类对象的成员变量。

import java.io.IOException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLMapper;

public class Department {
    private String name = null;
    private String code = null;

    public Department(String name, String code) {
        this.name = name;
        this.code = code;
    }

    // Getters and Setters
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
}

public class Person {
    private String name = null;
    private Integer age = null;
    private Department department = null;

    public Person(String name, Integer age, Department department) {
        this.name = name;
        this.age = age;
        this.department = department;
    }

    // Getters and Setters
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
    public Department getDepartment() {
        return this.department;
    }
    public void setDepartment(Department department) {
        this.department = department;
    }

    public static void main(String[] args) {
        try {
            ObjectMapper mapper = new YAMLMapper();
            Person person = new Person("David", 22, new Department("Computer Science", "CS"));

            // 生成YAML字符串
            System.out.println(mapper.writeValueAsString(person));
        } catch (IOException ex) {
            System.out.println(ex.getMessage());
        }
    }
}

上述程序的输出如下。读者可将其拷贝至YAML格式化页面检查其合法性。

---
name: "David"
age: 22
department:
  name: "Computer Science"
  code: "CS"

2 YAML文档解析

YAML解析的过程是YAML生成的逆过程。因此,在定义了数据类之后,就能很容易的将YAML字符串转换成Java对象。例如:

import java.io.IOException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLMapper;

public class Person {
    private String name = null;
    private Integer age = null;
    
    public Person(){
    }

    public Person(String name, Integer age) {
        this.name = name;
        this.age = age;
    }

    // Getters and Setters
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }

    public static void main(String[] args) {
        try {
            ObjectMapper mapper = new YAMLMapper();
            String yamlStr = "name: David\nage: 22\n";

            // 解析YAML字符串
            Person person = mapper.readValue(yamlStr, Person.class);
            System.out.println("name=" + person.getName());
            System.out.println("age=" + person.getAge());
        } catch (IOException ex) {
            System.out.println(ex.getMessage());
        }
    }
}

上述的程序输出为:

name=David
age=22

3 结语

本章介绍了如何使用Jackson对象映射的方法解析和生成YAML文档。因为Jackson库的底层提供了灵活的、可扩展的接口,Jackson自身能够适配解析JSON、XML、YAML和一些常用的文档格式,并且为应用程序提供了简洁的序列化和反序列化接口。使用Jackson代码库,能帮助开发人员在几行代码中完成文档的格式转换,非常方便。

上一章
下一章

注册用户登陆后可留言

Copyright  2019 Little Waterdrop, LLC. All Rights Reserved.