YAML Ain’t Markup Language (YAML)

> Markup Language (ML) > YAML Ain’t Markup Language (YAML)

1 - About

YAML minimizes the amount of structural characters in order to view and understand more easily the data.

For example:

  • indentation may be used for structure,
  • colons separate key: value pairs,
  • dashes are used to create “bullet” lists.

YAML want to be an official subset of JSON. Every JSON file is also a valid YAML file.

2 - Syntax

2.1 - Style

YAML supports the following style to denote scope :


2.1.1 - Indentation

2.1.2 - Flow

Flow style uses explicit indicators rather than indentation where:

2.2 - Structure

2.2.1 - Mapping

2.2.2 - Sequence

2.2.3 - Scalar

2.2.4 - Document

--- start of a document  (optional for the first document)
... end document without starting a new one, for use in communication channels

Example: Two Documents in a Stream (each with a leading comment)

# Ranking of 1998 home runs
- Mark McGwire
- Sammy Sosa
- Ken Griffey
# Team ranking
- Chicago Cubs
- St Louis Cardinals

3 - Runtime representation

YAML’s representation of native data structure is a rooted, connected, directed graph of tagged nodes.

3.1 - Node

A YAML node represents a single native data structure.

3.2 - Tag

Each node has a tag which serves to restrict the set of possible values the content can have.

  • Scalar
  • Sequence - The content of a sequence node is an ordered series of zero or more nodes. In particular, a sequence may contain the same node more than once. It could even contain itself (directly or indirectly).
  • Mapping - The content of a mapping node is an unordered set of key: value node pairs, with the restriction that each of the keys is unique.

4 - Library

I prefer SnakeYaml because:

  • the errors are more comprehesnible
  • Jackson use SnakeYaml

4.1 - Jackson

The object must have:

  • annotation
  • or getter and setter



4.1.1 - Read

InputStream inputStream = dataGenYmlTest.class.getResourceAsStream("/DataGen/dataGen.yml");
ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
TypeFactory typeFactory = mapper.getTypeFactory();
// For a collection`of object
CollectionType collectionType = typeFactory.constructCollectionType(List.class, myObjectToBuild.class);
List<myObjectToBuild> myObjectToBuilds = mapper.readValue(inputStream, collectionType);

4.1.2 - Write

ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
// Object To String
String yaml = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(objectToSerialize);
// Object To File
mapper.writeValue(new File("./objectSerialized.yml"), objectToSerialize);

5 - Documentation / Reference