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

3 thoughts on “Java Jackson – Json Polymorphism

  • January 18, 2017 at 12:44 am
    Permalink

    put the json output as well!!!

    Reply
  • March 21, 2017 at 8:25 pm
    Permalink

    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)

    Reply
  • July 4, 2017 at 11:54 am
    Permalink

    {
    “@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
    } ]
    }

    Reply

Leave a Reply

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