Skip to content

Flow Style (JSON‐like) YAML

Mihai A. 🇷🇴🇩🇪🇬🇧🇫🇷 edited this page Apr 29, 2024 · 2 revisions

Flow Style (JSON-like) YAML

Reading

We support reading and building of flow-style YAML. Take the following YAML (team.yml file):

architect: amihaiemil
devops: [
    rultor,
    0pdd,
    self-xdsd
  ]
developers: {
  architect: amihaiemil,
  developers: [vlad, christine],
  qa: [ana]
}

The Flow-style nodes will be printed accordingly:

YamlMapping team = Yaml.createYamlInput(
  new File("team.yml")
).readYamlMapping();
System.out.println(team);

Will print:

architect: amihaiemil
devops: [rultor, 0pdd, self-xdsd]
developers: {architect: amihaiemil, developers: [vlad, christine], qa: [ana]}

It is recommended to use the flow-style when you have short objects which can be easily printed on one line.

Building

To build flow-style nodes, we offer the .add(..., javax.json.JsonStructure) method in our builders (YamlMappingBuilder and YamlSequenceBuilder respectively). Using JSON as input made the most sense, because flow-style YAML Nodes can only contain other flow-style YAML Nodes.

To build the above YAML just do:

YamlMapping yaml = Yaml.createYamlMappingBuilder()
    .add("architect", "amihaiemil")
    .add(
        "devops",
        Json.createArrayBuilder()
            .add("rultor")
            .add("0pdd")
            .add("seld-xdsd")
            .build()
    ).add(
        "developers",
        Json.createObjectBuilder()
            .add("architect", "amihaiemil")
            .add("developers", /*createArrayBuilder()*/)
            .add("qa", /*createArrayBuilder()*/)
            .build()
    ).build();

For this, you will need to have an implementation of the JSON Pocessing (JSON-P)/JSR 374 Specification in your classpath (eo-yaml only offers the API of the spec, you need to add the implementation as dependency).