In this post, I’ll show you how to serialize (and deserialize) complex hierarchies of objects in Spray JSON. We’ll be dealing with ever so slightly complex tree structure. You’ll find out how to go beyond the JsonFormat[A] instances you get from calling jsonFormatn.

Let’s first begin by defining our tree. We’ll be modelling forms; a form contains fields or other forms as sub-forms. Both the form and the field need a label and an optional hint element. The field element needs to know what type of value it will hold (boolean, number, date, …). In code, this is quite nice structure:

sealed trait Element {
def label: String
def hint: Option[String]
}

This defines the base type Element that every node in our tree will share. Moving on, let’s outline the various kinds of fields we intend to support.

So, having a form: FormElement allows us to encode a form with any number of fields and any number of sub-forms and so on, recursively. Now, imagine that we have to turn this structure into JSON. Suppose our form instance is:

That seems easy. But what about the way back in? We need to be able to somehow discriminate between the field and form so that we can construct the entire tree back together. So, let’s modify the JSON to be:

In other words, we’ve wrapped every element document into a document with two fields: a String defining the kind and the actual payload. This gives us the ability to discriminate when we’re marshalling the instances into JSON and back.