Search code examples
javajacksonjackson-databind

Inheritance deserialisation with jackson in java


I have 3 child classes named CreditAccount, Savings Account & ChequingAccount that extends one superclass named Account.

I am trying to save all the users with their respective account details in a HashMap as follows:

public HashMap<Long, HashMap<String, Account>> userAndHisAccountsObject;

where the HashMap has UserID as key and a HashMap object as its value that contains AccountType as Key and respective account details its value. I am successfully able to serialize this object but when I try to deserialize it, it throws com.fasterxml.jackson.databind.exc.InvalidTypeIdException

can I get any solution to my issue? Thanks in advance.


Solution

  • The answer has indeed been provided in the comments by @hollpolloi with the link: https://github.com/FasterXML/jackson-docs/wiki/JacksonPolymorphicDeserialization

    When you are using inheritence and Jackson you need a way to tell jackson how to differentiate different JSON from each other, and how to decide which object-type (class) each one is. The problem is that Jackson can get confused with similar JSON payloads when there is no attribute that tells jackson what class should be used.

    Another good reference q/a is : Deserialize JSON with Jackson into Polymorphic Types - A Complete Example is giving me a compile error

    A very simple solution is to annotate your classes with something like the following:

    @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "@class")
    public abstract class Animal {
       ...
    }
    

    See also: