Skip to content

Block Style YAML

Mihai edited this page Mar 23, 2020 · 4 revisions

Block-Style YAML

This is the simplest form of YAML. A mapping or a sequence, no fancy stuff. Perfect for simple configuration files:

Building and printing Yaml:

YamlMapping yaml = Yaml.createYamlMappingBuilder()
    .add("architect", "amihaiemil")
    .add(
        "devops",
        Yaml.createYamlSequenceBuilder()
            .add("rultor")
            .add("0pdd")
            .build()
    ).add(
        "developers",
        Yaml.createYamlSequenceBuilder()
            .add("amihaiemil")
            .add("salikjan")
            .add("SherifWally")
            .build()
    ).build();

toString() methods are overriden to pretty-print the yaml, so the above yaml.toString() will print:

architect: amihaiemil
developers: 
  - amihaiemil
  - salikjan
  - SherifWally
devops: 
  - rultor
  - 0pdd

Of course, if you want to build a simple sequence, just start with Yaml.createYamlSequenceBuilder().

Reading

Reading all sorts of YAML happens through the Yaml.createYamlInput(...) method. This method is overloaded to accept a String, a File or an InputStream.

Put the above YAML in a file called team.yml and read it:

YamlMapping team = Yaml.createYamlInput(
    new File("mapping.yml")
).readYamlMapping();
String architect = team.string("architect");
YamlSequence devs = team.yamlSequence("developers");
YamlSequence devops = team.yamlSequence("devops");
Clone this wiki locally