YAML Ain’t Markup Language (YAML)

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.

Syntax

Style

YAML supports the following style to denote scope :

Indentation

Flow

Flow style uses explicit indicators rather than indentation where:

Structure

Mapping

Sequence

Scalar

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

Runtime representation

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

_

Node

A YAML node represents a single native data structure.

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.

Library

SnakeYaml

I prefer SnakeYaml because:

  • the errors are more comprehesnible
  • Jackson use SnakeYaml

Jackson

The object must have:

  • annotation
  • or getter and setter

Dependencies

<dependency>
	<groupId>com.fasterxml.jackson.core</groupId>
	<artifactId>jackson-databind</artifactId>
	<version>2.6.3</version>
</dependency>
<dependency>
	<groupId>com.fasterxml.jackson.dataformat</groupId>
	<artifactId>jackson-dataformat-yaml</artifactId>
	<version>2.9.2</version>
</dependency>

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);

Write

ObjectMapper mapper = new ObjectMapper(new YAMLFactory());

// Object To String
String yaml = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(objectToSerialize);
System.out.println(yaml);

// Object To File
mapper.writeValue(new File("./objectSerialized.yml"), objectToSerialize);

Vs Json

Documentation / Reference


Powered by ComboStrap