SDA Commons Shared YAML
This module contains a class YamlUtil
providing static methods for YAML-file handling.
Usage
The YamlUtil
provides an overloaded method for loading YAML-files and one for serialization.
A single object
Given the following YAML-file
| message: "Hello"
attribute: "attribute1"
|
it's possible to load and serialize a single object:
1
2
3
4
5
6
7
8
9
10
11
12
13 | import org.sdase.commons.shared.yaml.YamlUtil;
class MyClass {
public static void main(final String[] args) {
InputStream resource = this.getClass().getClassLoader().getResourceAsStream("sample.yml");
TestBean tb = YamlUtil.load(resource, TestBean.class);
// ...
String serializedClass = YamlUtil.writeValueAsString(tb);
}
}
|
List of objects
To load a list of objects from a YAML-file like
| - message: Hello World!
attribute: Foo
id: 123
- message: Hello Universe!
attribute: Bar
id: 456
|
use a TypeReference<T>
as the second parameter:
| List<TestBean> beans = YamlUtil.load(resource, new TypeReference<List<TestBean>>() {});
|
Multiple documents
To load a YAML-file that contains multiple YAML-documents, like
| message: Hello World!
attribute: Foo
id: 123
---
message: Hello Universe!
attribute: Bar
id: 456
|
use YamlUtil.loadList()
:
| List<TestBean> beans = YamlUtil.loadList(resource, TestBean.class);
|