Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 201
DevShot Avatar asked Mar 28 '26 01:03

DevShot


1 Answers

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:

  • https://www.logicbig.com/tutorials/misc/jackson/jackson-json-type-info-annotation.html
like image 113
Menelaos Avatar answered Mar 31 '26 05:03

Menelaos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!