A special case for de-serialize Polymorphic class by Jackson

A special case for de-serialize Polymorphic class by Jackson

 

By WZh   Apr 2015

A very good article about the de-serialize the data in Jackson from Json to JAVA is already at this article

  1. http://programmerbruce.blogspot.co.uk/2011/05/deserialize-json-with-jackson-into.html

But a special case we have met is not in that article. Input json sample:

//   {

“type”:”dog”,

//     “animal”:

//           {“name”:”Spike”,

// “breed”:”mutt”,

//            “leash_color”:”red”}

}

or

//   {

“type”:”cat”,

//     “animal”:

//           {“name”:”Fluffy”,

//           “favorite_toy”:”spider ring”}

//   }

This means type is not inside the abstract class itself, type is controlled by parent class fields and also we want to use getter and setter in the parent class for “type” in other java code, to type must be cleared defined at Zoo class as Java field.

Here is the solution after research!

class Zoo

{

private String type;

private Animal animal;  

@JsonTypeId

public String getType() {

return type;

}

public void setType(String type) {

this.type = type;

}

@JsonTypeInfo(

use = JsonTypeInfo.Id.NAME,

include = JsonTypeInfo.As.EXTERNAL_PROPERTY,

property = “type”)

@JsonSubTypes({     @Type(value = Cat.class, name = “cat”),  

    @Type(value = Dog.class, name = “dog”) })  

public void setAnimal ( Animal value) {

this.animal = value;

}

public Animal getAnimal () {

return animal;

}

}

abstract class Animal

{

}

class Dog extends Animal

{

  public String name;

  public String breed;

  public String leashColor;

}

class Cat extends Animal

{

  public String name;

  public String favoriteToy;

}

the most important thing in the code is :

  1. @JsonTypeId set to getter for “type” and let the jackson do not create duplicate “type” in the json
  2. @JsonTypeInfo defined with JsonTypeInfo.As.EXTERNAL_PROPERTY to let the Animal class can be controlled by the external property “type” to do the Polymorphic
  3. @JsonTypeInfo is put to the setter of the abstract class to contorl the Polymorphic
Advertisements