Jackson vs. Gson vs. JSON-B | Java JSON Polymorphic type handling

In this article we will compare polymorphic type handling in different JSON binding libraries in Java i.e. Jackson vs. Gson vs. JSON-B (Eclipse Yasson)

For complete comparison of top JSON libraries & their features, visit below article.

Jackson vs. Gson vs. JSON-B vs. JSON-P vs. org.JSON vs. Jsonpath | Java JSON libraries features comparison

Polymorphic JSON bound POJOs

As Java is object oriented language, JSON bound POJOs might have polymorphic nature. For example, Car (abstraction) with Honda & Tesla as concrete implementations.

Test JSON

For above POJOs, we will use these JSONs to test different libraries.



Jackson

In jackson, to achieve polymorphic handling of JSON bound POJOs, just add these annotations on Car.java i.e. abstract class. To identify subclass to use during deserialization, value of ‘make’ field from subclasses will be used to determine which sub class will be used to instantiate object.

Now lets deserialize JSON using above annotated POJO & test json files.



GSON

GSON does not provide out of the box way to handle polymorphic type handling, but we can create custom deserializer to achieve this effect.

Now lets deserialize JSON using above CarDeserializer & test json files.



JSON-B

JSON-B also does not provide specific easy annotation to achieve this so we can create deserializer to achieve this.

Put annotation on Car.java to user CarDeserializer

Now lets deserialize JSON using above CarDeserializer & test json files.



Leave a Reply

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