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.