Java snakeyaml

From wikinotes

Documentation

official docs https://bitbucket.org/asomov/snakeyaml/wiki/Home
tutorial https://www.baeldung.com/java-snake-yaml

dependency manager

maven

<dependency>
    <groupId>org.yaml</groupId>
    <artifactId>snakeyaml</artifactId>
    <version>1.24</version>
</dependency>

Usage

load simple/homogenous data


From File

import org.yaml.snakeyaml.Yaml;
import java.util.Map;

Yaml parser = new Yaml();
FileInputStream stream = new FileInputStream("/path/to/file.yml");
Map<String, String> = yaml.load(stream);

From String

import org.yaml.snakeyaml.Yaml;
import java.util.Map;

Yaml yaml = new Yaml();

// dynamic type (print only)
Object obj = yaml.load("a: 1\nb: 2\nc:\n  - aaa\n  - bbb");
System.out.println(obj);

// explicitly setting type
Map<String, String> data = yaml.load("a: 'abc'\n");
System.out.println(data.get("a"));

load complex/heterogenous/nested data


snakeyaml allows you to assign deserialized data to fields on objects. This solves the issue of constantly needing to cast data, and also performs simple type validation on your yaml file.

Note each class must reside in it's own file, they also cannot be nested classes.

Simple Example

import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.Constructor;

class Customer
{
    public String name;
    public Integer age;
}

// loading data
Constructor constructor = new Constructor(Customer.class);
Yaml yaml = new Yaml(constructor);

String data = "\n"
    + "name: will\n"
    + "age:  32\n";

Customer customer = yaml.load(data);
System.out.println(customer.name);
System.out.println(customer.age);

Complex Example

import java.util.List;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.Constructor;


class Customer
{
    public String name;
    public Integer age;
}

class CustomerList
{
    public String version;
    public List<Customer> customers;
}

// deserialize
String data = "\n"
    + "version: 1.0.0\n"
    + "customers:\n"
    + "  -\n"
    + "    name: will\n"
    + "    age:  32\n"
    + "  -\n"
    + "    name: alex\n"
    + "    age:  30\n";
Constructor constructor = new Constructor(CustomerList.class);
Yaml yaml = new Yaml(constructor);
CustomerList customers = yaml.load(data);

// print data
System.out.println(customers.version);
for (Customer c: customers.customers){
    System.out.println(String.format("%s: %s", c.name, c.age));
}


dump

import org.yaml.snakeyaml.Yaml;
import java.util.Map;

// build data
Map<String, String> data = new HashMap<String, String>();
data.put("name", "Pushkin");

// serialize
Yaml yaml = new Yaml();
String output = yaml.dump(map);
System.out.println(output);