java - 将 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;
}
提前致谢!
解决方案
如果你想使用 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
推荐阅读
- sql - 年份之间的匹配范围
- spring - UTF-8 编码从 Spring 服务器加载为 ISO-8859-1
- laravel - Laravel 404 未找到 - 但路线存在
- c# - C# 在未知模块中使用互操作未处理的“System.IO.FileNotFoundException”加载 Excel 文件
- node.js - 使获得拒绝值成为可能
- amazon-web-services - 限制 AWS unauth cognito 用户的使用
- flutter - Flutter/dart 和静态 Widget 方法。模式不好?
- python - Python beautifulsoup:从 img src 获取占位符
- excel - 通过 Excel 发送电子邮件
- python - 有没有比这更好的方法来编写“依赖参数”的 Python 函数?