简体   繁体   中英

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 ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM