Skip to content

Automatic serialization with Jackson

Nathaniel Fischer edited this page Mar 19, 2016 · 1 revision

Default implementation of representationBuilder

The HalResource interface requires you to implement the representationBuilder method to configure the properties, links and embeds for your object. However, this can be done for you by implementing JacksonHalResource instead of HalResource.

This allows for quick creation of objects which have a resource identifier, but no links from them to other resources. The default method uses Jackson to map your object's fields into HAL properties.
If your object contains many more properties than it does linked or embedded resources, you might find it useful to invoke this default method and then modify the builder to suit you; rather than building the entire representation yourself. An example of how to do this with java 8 looks like this

public HalRepresentationBuilder representationBuilder() {
		return HalResource.super.representationBuilder()
				.removeProperty("basket")
				.removeProperty("customer")
				.addLink("basket", basket)
				.addLink("customer", customer);
	}

Here HalResource.super.representationBuilder() is creating the builder automatically; however it adds everything from the instance as a property and we wanted "basket" and "customer" to be links, so we need to correct it slightly with removeProperty and then re-add those fields as links.
More info on invoking default methods from subclass implementations can be found here.

Configuring the ObjectMapper

There are three ways to change the ObjectMapper used for auto-serializing resources.

Pass a mapper at method invocation.

JacksonHalResource adds the methods representationBuilder(ObjectMapper) and asEmbedded(ObjectMapper, String...). As you would expect, if you pass an ObjectMapper to these methods, that mapper will be used for building the representation.

Implement defaultMapper()

JacksonHalResource also adds a defaultMapper() method. If you implement this method in your class, the mapper it returns will be used to build the representation for that class.

Set the mapper globally

HalRepresentation#useMapper(ObjectMapper) allows you to set the mapper used for all hate serialization.

No self href

By default a self referential link is created. If you don't want your resource to have a self link, just return null when you implement the location() method.