Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson inheritance and deserialization

I am writing an API on top of Spring Web MVC/Spring Hateoas and even if the deserialization of simple class hierarchy works like a charm, I cannot manage to deserialize Json input to the proper type using jackson. Here is my class hierarchy :

public class A {
    protected String fieldA;
}

public class B extends A {
    protected String fieldB;
}

public class C extends A {
    protected String fieldC;
}

Before everybody sends me to the many other similar questions on SO, the main difference here is that A is concrete. In other words, Jackson has to choose between 3 implementations by using the json fields as tie breakers.

Basically, how can I configure Jackson to have it deserialize :

{
    "fieldA": "asdf"
} 

to an instance of A, and

{
    "fieldA": "asdf",
    "fieldB": "asdf"
} 

to an instance of B ?

like image 737
Maxime Avatar asked Feb 11 '26 22:02

Maxime


1 Answers

There is no way to do that automatically: all automatic polymorphic type handling relies on type discriminator of some kind (type property, most commonly). Ability to use content-based heuristics has been requested, but so far no one has presented a viable plan (or contributions) for implementing functionality like this.

To handle it you will probably need to write a custom JsonDeserializer and detect type yourself. It might be possible to use ConvertingDeserializer, to let Jackson bind JSON into JsonNode or java.util.Map first, and then just extract it yourself.

like image 169
StaxMan Avatar answered Feb 13 '26 16:02

StaxMan