Custom Jackson Polymorphic Deserialization without Type Metadata

At SportsLabs we regularly encounter proprietary, non-standard APIs and formats. Our job is to integrate with these APIs, normalize them, and distribute the data in web- and mobile-friendly web services.

One of the scenarios we often encounter is a provider supplying multiple resource JSON-based APIs that share a lot of the same data in their responses, but without any particular field dedicated to identying the type of the resource e.g.

{
...
	"common": "a common field within multiple resource responses",
	"one": "one is a field only within this response type"
...
}

and

{
...
	"common": "a common field within multiple resource responses",
	"two": "two is a field only within this response type"
...
}

Instead of mapping 1-to-1 with these APIs, we often try to follow DRY principles and model them as implementations of a common polymorphic abstraction.

When using Jackson for polmorphic deserialization and not being in control of the API response data, the lack of any kind of type identifier requires a different solution.

One of the ways we’ve addressed this problem is to identify fields and properties that are unique to a particular resource API’s response.

We then add this field to a registry of known unique-property-to-type mappings and then, during deserialization, lookup the response’s field names to see if any of them are stored within the registry.

Read on →

Building a Custom Jackson Deserializer

A partner recently provided a useful HTTP-based API for me at short notice.

The API returned simple JSON representations of the current state of various events they had periodically ingested from our REST APIs.

A decision they made was to use "yes"/"no" values in the response, rather than booleans e.g.

{
...
	"exists": "yes",
	"has_ended": "no"
...
}

I had written a Spring Social-based API client to interact with their API but wanted to deserialize their API response representation into a POJO that followed Java convention.

Jackson is a great Java library for processing JSON data format. It’s quite straightforward to use it to solve a problem like the above with a custom JsonDeserializer.

Read on →