Class YamlSerializer

All Implemented Interfaces:
Function<Object,String>, ThrowingFunction<Object,String>, ArrayRecordWritable, RecordWritable, YamlMetaProvider
Direct Known Subclasses:
YamlSerializer.Readable

Serializes POJO models to YAML.
Media types

Handles Accept types: application/yaml, text/yaml

Produces Content-Type types: application/yaml

Description

The conversion is as follows...

  • Maps (e.g. HashMaps, TreeMaps) are converted to YAML mappings.
  • Collections (e.g. HashSets, LinkedLists) and Java arrays are converted to YAML sequences.
  • Strings are converted to YAML scalars.
  • Numbers (e.g. Integer, Long, Double) are converted to YAML numbers.
  • Booleans are converted to YAML booleans.
  • nulls are converted to YAML nulls.
  • arrays are converted to YAML sequences.
  • beans are converted to YAML mappings.

The types above are considered "YAML-primitive" object types. Any non-YAML-primitive object types are transformed into YAML-primitive object types through ObjectSwaps associated through the MarshallingContext.Builder#swaps(Class...) method. Several default transforms are provided for transforming Dates, Enums, Iterators, etc...

This serializer provides several serialization options. Typically, one of the predefined DEFAULT serializers will be sufficient. However, custom serializers can be constructed to fine-tune behavior.

Example:

// Use one of the default serializers to serialize a POJO String yaml = YamlSerializer.DEFAULT.write(someObject); // Create a custom serializer YamlSerializer serializer = YamlSerializer.create().build(); // Clone an existing serializer and modify it to use whitespace serializer = YamlSerializer.DEFAULT.copy().ws().build(); // Serialize a POJO to YAML yaml = serializer.write(someObject);

Example output (LinkedHashMap of name/age):

name: Alice age: 30

Complex (nested bean + array; bean properties are sorted alphabetically by default):

address: city: Boston state: MA street: "123 Main St" age: 30 name: Alice tags: - a - b - c

Limitations compared to JSON

The YAML serializer has fewer configuration options than JsonSerializer:

  • No compact single-line output mode; YAML is always emitted in block-style (indentation-based) format.
  • No equivalent to JSON's simple mode or attribute quoting style variants (single vs double quotes).
  • No strict vs lax output modes; YAML output follows a consistent, human-readable style.
Notes:
  • This class is thread safe and reusable.
See Also: