Wiki

Clone wiki

snakeyaml / FAQ

Frequently Asked Questions

Dictionaries without nested collections are not dumped correctly

Why does

Yaml yaml = new Yaml();
String document = "  a: 1\n  b:\n    c: 3\n    d: 4\n";
System.out.println(document);
System.out.println(yaml.dump(yaml.load(document)));
give
  a: 1
  b:
    c: 3
    d: 4

a: 1
b: {c: 3, d: 4}

It's a correct output despite the fact that the style of the nested mapping is different.

By default, SnakeYAML chooses the style of a collection depending on whether it has nested collections. If a collection has nested collections, it will be assigned the block style. Otherwise it will have the flow style.

If you want collections to be always serialized in the block style, set the parameter defaultFlowStyle of DumperOptions to block. For instance,

DumperOptions options = new DumperOptions();
options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
Yaml yaml = new Yaml(options);
String document = "  a: 1\n  b:\n    c: 3\n    d: 4\n";
System.out.println(yaml.dump(yaml.load(document)));

a: 1
b:
  c: 3
  d: 4

You can find an example here

Binary Data

byte[] is represented as binary. Also when a String contains at least one non-printable character the !!binary type is emitted.

Binary scalar is parsed as byte[]. If a JavaBean has a property of type String it can be parsed as String even though it was converted to !!binary in the YAML document.

An example can found here.

JSON support

JSON is a subset of YAML 1.2, SnakeYAML implements YAML 1.1 at the moment. It means that not all JSON documents can be parsed.

Usually, adding a space after the colon solves the compatibility issue, instead of

{"foo":"bar"}
use
{"foo": "bar"}

Why SnakeYAML does not use something like XmlAdapter or JsonSerializer/JsonDeserializer or Annotations or XXX ?

It may. SnakeYAML has a low level API which can be used to create actual Java structures. Feel free to make a proposal and implementation.

Why sometimes SnakeYAML complains that there is no single argument constructor even I do not expect it to be ?

Well, to support type inference SnakeYAML tries different ways to create a Java instance in a sequence. The error message comes from the very last rule which failed. Often trying "single argument constructor" is the last chance to succeed. For instance, a YAML document:

properties:
  - port: 80
Here properties is a Map, but SnakeYAML cannot create the Map because the value for the Map is a List with a single value port: 80. Removing the dash solves the issue:
properties:
  port: 80

Updated