Skip to main content

YAML Serializers

The YamlSerializer class is used to serialize POJOs into YAML.

The class hierarchy for the builder of this serializer is:

Context.BuilderMarshallingContextable.BuilderMarshallingTraverseContext.BuilderSerializer.BuilderWriterSerializer.BuilderYamlSerializer.Builder

Refer to the builder javadocs for configurable settings.

The following pre-configured serializers are provided for convenience:

YamlSerializerDEFAULTDEFAULT_READABLE

Usage​

// Serialize a POJO to YAML
String yaml = YamlSerializer.DEFAULT.write(myBean);

// Create a custom serializer
YamlSerializer s = YamlSerializer.create()
.addBeanTypes()
.trimNullProperties()
.build();
String yaml = s.write(myBean);

// Use the Yaml marshaller for convenience
String yaml = Yaml.of(myBean);

Output Style​

The YAML serializer produces block-style output by default. Beans and maps are formatted with each property on its own line, and collections/arrays use the YAML block sequence marker (-).

The DEFAULT_READABLE variant produces the same output as DEFAULT since YAML is inherently human-readable through its indentation-based format.

For example, a bean with age, name, tags and status (an enum) properties is written as:

age: 30
name: Alice
status: ACTIVE
tags:
- a
- b

Serializer settings​

The YAML serializer has one format-specific setting; everything else is inherited from WriterSerializer / Serializer / MarshallingContext (swaps, keepNullProperties(), useWhitespace(), etc.).

Builder methodDefaultDescription
addBeanTypesYaml() / addBeanTypesYaml(boolean)falseAdd _type properties to beans whose type cannot be inferred through reflection. Overrides the generic addBeanTypes() setting for this serializer only (useful inside a SerializerSet).

The addBeanTypes default can also be set with the YamlSerializer.addBeanTypes environment setting.

Null properties are omitted by default; keepNullProperties() writes them as null:

YamlSerializer s = YamlSerializer.create().keepNullProperties().build();
// ... nick: null

Annotations​

@YamlConfig applies settings on a REST class or method (see Context Annotations).

AttributeDescription
addBeanTypes"true" / "false" (default). Maps to addBeanTypesYaml(boolean). Supports variables such as $C{myConfigVar}.
rankOrdering relative to other config annotations.
@Rest
@YamlConfig(addBeanTypes="true")
public class MyResource extends BasicRestServlet { ... }

Limitations compared to JSON​

  • No compact single-line output mode; YAML is always emitted in block style.
  • No simple-mode / quoting-style variants (single vs double quotes).
  • No strict vs lax output modes.