Java Jackson – Json Polymorphism

Also see json simple org.json

Jackson provides a way to maintain sub type information while serializing java objects. It is possible to recreate the exact sub type. The type information can be embedded into the json as a property. In the example below we create a zoo, that has a list of animals. The animal may be an elephant or a lion, and they both extend the Animal abstract class. While deserializing we want to create the exact animal type. We also demonstrate the use of @JsonTypeInfo and @JsonSubTypes annotations.

Data Serialization and Polymorphism Example

Before we look at the various classes, lets also see how to deserialize this

Zoo class

Animal Abstract class

Lion class

Elephant class

Java Jackson – Json Polymorphism

3 thoughts on “Java Jackson – Json Polymorphism

  1. Hi

    In the class DeSerializeExample1 if you trying get name of animal it gets an error :

    –> System.out.println(zoo.animals.get(0).name); ==> result : “null”

    –> System.out.println(zoo.animals.get(0).name.toString());
    Exception in thread “main” java.lang.NullPointerException
    at polymorphismZoo.DeSerializeExample1.main(DeSerializeExample1.java:19)

  2. {
    “@class” : “Zoo”,
    “name” : “Samba Wild Park”,
    “city” : “Paz”,
    “animals” : [ {
    “@class” : “Lion”,
    “name” : “Simba”,
    “sound” : “Roar”,
    “type” : “carnivorous”,
    “endangered” : true
    }, {
    “@class” : “Elephant”,
    “name” : “Manny”,
    “sound” : “trumpet”,
    “type” : “herbivorous”,
    “endangered” : false
    } ]
    }

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to top
Bitnami