[Jackson] Json to Java Conversion with Ploymorphism

Converting Json String to Java Object is never straight forward, especially when polymorphism is involved. Consider the below interface:

It has two sub classes:

We now will try to convert a Json String to a Java Object:

The full test can be found here: https://github.com/paawak/blog/blob/master/code/json-inheritance-demo/src/test/java/com/swayam/demo/json/polymorphic/noannotation/PolymorphicJsonTest.java

This will immediately throw the below exception:

The reason is, the Json String does not have any information about the specific subclass. This can be very easily overcome by forcing the type information while serializing Java to Json, by using the @JsonTypeInfo annotation. This should be placed on the interface or the abstract class as shown below:

Now, the below code would work:

The full test can be found here: https://github.com/paawak/blog/blob/master/code/json-inheritance-demo/src/test/java/com/swayam/demo/json/polymorphic/withannotation/PolymorphicJsonTest.java

The entire source code for this can be found here: https://github.com/paawak/blog/tree/master/code/json-inheritance-demo

 

Leave a Reply

Your email address will not be published. Required fields are marked *