Jackson 2.12 Most Wanted (1/5):

Deduction-Based Polymorphism

@cowtowncoder
2 min readDec 3, 2020

(part 1 of “Deeper Dive on Jackson 2.12” mini-series — see “Jackson 2.12 Features” for context)

The oldest open feature request jackson-databind#43 — filed in 2012 — was to support polymorphic types that do not have dedicated “Type Id” but where expected type can instead be deduced based on simple existence/absence of properties.

This is in contrast to existing “classic”, type id-based approach, where type definitions look something like:

@JsonTypeInfo(use=Id.NAME, include=As.PROPERTY, property="@type")
@JsonSubTypes({ ... })
abstract class Animal {
public String name;
}
@JsonTypeName("dog")
public class Dog extends Animal {
public DogFunction function; // BIRD_DOG, GUARD_DOG
}
@JsonTypeName("cat")
public class Cat extends Animal {
public boolean likesMilk;
public boolean hairLength;
}

(bear with me — I am not good at Object Modeling of animal kingdom :))
and JSON that would match such model, to express a single Animal could look like:

{ "@type" : "dog",
"name" : "Bubba",
"function" : "GUARD_DOG"
}

Although specific details of what is used as Type Id (class name or logical type id) and inclusion mechanism (as-property, wrapper-array, wrapper-object, “external” property) vary, all existing approached required specific identifier to be written and used.

But looking at case above, could Jackson not just observe that for “dog”, there has to be function property (Cats do not have such properties!); and conversely for cats finding either likesMilk or hairLength would prove “cat-ness” of the Object?

And yes: if your type definitions are nicely non-overlapping, this would work: all you have to change is this:

@JsonTypeInfo(use=Id.DEDUCTION)
@JsonSubTypes({ ... })
abstract class Animal {
public String name;
}

and, well, it should be a solid case of “Just Works! (tm)” in action.
For another simple usage example you can have a look at TestPolymorphicDeduction.java.
This being a very new feature, more testing would definitely be useful as well; please report any issues you might find. :)

And finally: shout out to Marc Carter for contributing this exciting new feature!

--

--

@cowtowncoder

Open Source developer, most known for Jackson data processor (nee “JSON library”), author of many, many other OSS libraries for Java, from ClassMate to Woodstox