Arbitrary Java object serialization to YAML

There are several good options for java object serialization and deserialization. One of these is to use the YAML data serialization standard.

YAML (rhymes with “camel“) is a human-friendly, cross language, Unicode based data serialization language designed around the common native data types of agile programming languages. It is broadly useful for programming needs ranging from configuration files to Internet messaging to object persistence to data auditing.

There are also several Java libraries that implement the YAML standard (as listed on yaml.org).

  • JvYaml
  • SnakeYAML
  • YamlBeans
  • JYaml

For the purpose of this article we’ll be using SnakeYAML as a solid modern implementation of the YAML 1.1 standard.

Consider the following simple example:

Source: Weapon.java

This Java bean can be serialized and deserialized with just the following code:

Source: WeaponTest.java

Simple Java beans are automatically serialized and deserialized, the data looks like this:

Of course in reality things are not always that simple. Your domain model may contain types that are not Java beans like java.net.URL, java.util.UUID, java.net.InetAddress and others. In this case the serialization process will ignore the non-bean objects and deserialization will fail altogether.

Fortunately SnakeYAML’s represent and construct functionality can easily be extended. Consider the following more complex example:

Source: Cyborg.java

Now we have non-bean types and java.util.Collection. To handle serialization and deserialization properly we need to use custom representer and constructor.

The representer takes the non-bean objects and transforms them into custom-tagged scalars. Also RepresentInetAddress is registered for both Inet4Address and Inet6Address to handle both protocols.

Source: ApplicationRepresenter.java

The constructor does exactly the opposite of the representer does.

Source: ApplicationConstructor.java

Our custom representer and constructor are passed to the constructor of the YAML processor. Putting everything together looks like this:

Source: CyborgTest.java

Now the type hierarchy is represented in YAML like this:

As you can see the non-bean type values are tagged with custom tags: !inet and !uuid. That’s how the YAML document is later properly deserialized.

Leave a Reply

Your email address will not be published. Required fields are marked *