Jackson—yaml文件内容转换成POJO

在日常coding的过程中,我们会碰到一些需要读取自定义yaml文件的需求。Spring框架中集成了Jackson序列化框架,而Jackson也正好可以读取yaml文件。

依赖


    com.fasterxml.jackson.dataformat
    jackson-dataformat-yaml
    2.9.8


1. 序列化为普通的Bean

Sudent.java:

public class Student{
    private String name;
    private int age;
}

student.yaml

name: 张三
age: 5

读取student.yaml文件只需要用YamlFactory初始化一个ObjectMapper

    ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory());
    InputStream fis = new ClassPathResource("student.yaml").getInputStream();
    objectMapper.readValue(fis,Student.class)

2. 序列化为List

list_student.yaml:

  - name: 张三
    age: 5
  - name: 李四
    age: 6

读取List需要用到ObjectReader,用ObjectMapper可得到

    ObjectReader objectReader = objectMapper.readerForListOf(Student.class);
    InputStream fis = new ClassPathResource("list_student.yaml").getInputStream();
    objectReader.readValue(fis);

序列化为map

map_student.yaml:

student1:
    name: 张三
    age: 5
student2:
    name: 李四
    age: 6

读取Map与读取List方法类似

    ObjectReader objectReader = objectMapper.readerForListOf(Student.class);
    InputStream fis = new ClassPathResource("map_student.yaml").getInputStream();
    objectReader.readValue(fis);

读取多key的Map和List结合的yaml文件

仅提供思路,并不一定是最优解。
complex_student.yaml:

class1:
    - teacher1:
          name: 张三
          age: 5
    - teacher2:
          name: 张三
          age: 5

可以看到上面的yaml文件中,最外层的key是class1,里面的value是一个list,而list每项里面又是个map,整体的结构为Map>>。我们没必要用一个显示的数据结构去接收整个yaml文件,可以拆分成JsonNode去读取。

      fis = new ClassPathResource("complex_student.yaml").getInputStream();
      JsonNode jsonNode = objectMapper.readTree(fis).get("class1");
      ObjectReader objectReader = objectMapper.readerForListOf(ObjectNode.class);
      List objectNodes = objectReader.readValue(jsonNode);
      JsonNode currentNode = null;
      for (ObjectNode node : objectNodes) {
        if (Objects.nonNull(node.get("teacher1"))) {
          currentNode = node.get(prod);
        }
      }
      objectReader = objectMapper.readerFor(Student.class);
      objectReader.readValue(currentNode);

以上可以读取到class1 -> teacher1下面的学生姓名,实际操作中,两层map的key可以以参数的形式传进来。

你可能感兴趣的:(Jackson—yaml文件内容转换成POJO)