Skip to content

SDA Commons Shared YAML

javadoc

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

1
2
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

1
2
3
4
5
6
- message: Hello World!
  attribute: Foo
  id: 123
- message: Hello Universe!
  attribute: Bar
  id: 456

use a TypeReference<T> as the second parameter:

1
List<TestBean> beans = YamlUtil.load(resource, new TypeReference<List<TestBean>>() {});

Multiple documents

To load a YAML-file that contains multiple YAML-documents, like

1
2
3
4
5
6
7
message: Hello World!
attribute: Foo
id: 123
---
message: Hello Universe!
attribute: Bar
id: 456

use YamlUtil.loadList():

1
List<TestBean> beans = YamlUtil.loadList(resource, TestBean.class);