Yaml - SnakeYaml Library (Java)

About

SnakeYaml is a java library that manages yaml document.

Example

Object Serialization

Object to read or write must be:

  • a java bean (ie getter and setter + public properties)
  • a LinkedList
  • a HashMap

Read

Log file:

---
Time: 2001-11-23 15:01:42 -5
User: ed
Warning:
  This is an error message
  for the log file
---
Time: 2001-11-23 15:02:31 -5
User: ed
Warning:
  A slightly different error
  message.
---
Date: 2001-11-23 15:03:17 -5
User: ed
Fatal:
  Unknown variable "bar"
Stack:
  - file: TopClass.py
    line: 23
    code: |
      x = MoreObject("345\n")
  - file: MoreClass.py
    line: 58
    code: |-
      foo = bar

With SnakeYaml, the data object are LinkedList.

  • Dependency:
<dependency>
    <groupId>org.yaml</groupId>
    <artifactId>snakeyaml</artifactId>
    <version>1.20</version>
</dependency>
  • Code
public void testLoadManyDocuments() throws FileNotFoundException {
    InputStream input = new FileInputStream(new File(
            "src/test/resources/specification/example2_28.yaml"));
    Yaml yaml = new Yaml();
    for (Object data : yaml.loadAll(input)) {
        System.out.println(data);
    }
}
{Time=Fri Nov 23 21:01:42 CET 2001, User=ed, Warning=This is an error message for the log file}
{Time=Fri Nov 23 21:02:31 CET 2001, User=ed, Warning=A slightly different error message.}
{Date=Fri Nov 23 21:03:17 CET 2001, User=ed, Fatal=Unknown variable "bar", Stack=[{file=TopClass.py, line=23, code=x = MoreObject("345\n")
}, {file=MoreClass.py, line=58, code=foo = bar}]}

where:

  • curly brace { } are indicating a map
  • and [] indicates a sequence

Documentation / Reference


Powered by ComboStrap