首页 > 解决方案 > 将 YAML 文件解析为 Java 类

问题描述

我有一个 YAML 文件,我需要做的是创建适当的类,以便我可以使用以下代码解析它:

InputStream inputStream = null;
        try {
            inputStream = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        Yaml yaml = new Yaml();
        Root myYaml = yaml.loadAs(inputStream, Root.class);

这是 YAML 文件:

project:
  name: My Software Project
  description: The description of the project
suites:
  - BackEndTests:
    - Test1:
        enabled: true
        command: echo Test
    - Test2:
        enabled: true
        command: echo Test 2
        description: This test does something too
  - UITests:
    - Test3:
        enabled: true
        command: echo Test 3
        description: Hello world
    - Test4:
        enabled: false
        command: echo Test 4

我创建了以下类:

public class Root {
     private Project project;
     private List<Suite> suites;
}
// setters and getters

public class Project {
     private String name;
     private String description;
}
// setters and getters

public class Suite {
     private String name;
     private List<Test> tests;
}
// setters and getters

public class Test {
     private boolean enabled;
     private String command;
     private String description;
}
// setters and getters

我的应用程序收到此错误消息,使用 Spring Boot 构建: 单击此处查看完整的错误消息

我总是为每个类包含 setter、getter 甚至构造函数。有人可以建议如何构造类,以便我可以解析 YAML 文件而不会出现任何错误?另外,如果我在类中添加额外的字段(除了 yaml 中列出的这些),是否可以,因为我需要稍后将它们用于其他目的?一个例子:

public class Project {
     private Integer id; // adding field that is not contained in the yaml
     private String name;
     private String description;
}

提前致谢!

标签: javayamlsnakeyaml

解决方案


如果你想使用 YAML 格式,那么正确的格式是

project:
  description: The description of the project
  name: My Software Project
suites:
  - name: BackEndTests
    tests:
      - command: echo Test
        enabled: true
        name: Test1
      - command: echo Test 2
        description: This test does something too
        enabled: true
        name: Test 2
  - name: UITests
    tests:
      - command: echo Test 3
        description: Hello world
        enabled: true
        name: Test3
      - command: echo Test 4
        enabled: false
        name: Test4

课程将是:

public class Root {
     private Project project;
     private List<Suite> suites;
}
// setters and getters

public class Project {
     private String name;
     private String description;
}
// setters and getters

public class Suite {
     private String name;
     private List<Test> tests;
}
// setters and getters

public class Test {
     private String name;
     private boolean enabled;
     private String command;
     private String description;
}
// setters and getters

推荐阅读