1

My Json can be:

{                                     
    "bird": "Owl",
    "Animal": {
        "type": "Dog",
        "breed": "mutt"
    }
}

Or

{
    "bird": "Owl",
    "Animal": {
        "type": "Cat",
        "color": "white"
    }
}

Class for Json,

Class ABC {

     public String bird;

     Animal animal;

}


@JsonIgnoreProperties(ignoreUnknown = true)
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY,property = "type")
@JsonSubTypes({
    @JsonSubTypes.Type(value=Dog.class,name="dog"),
    @JsonSubTypes.Type(value=Cat.class,name="cat") }
)

Class Animal {

    public String type;

}

Class Dog extends Animal {

   public String breed;

}

Class Cat extends Animal {

   public String color;

}

when i read json,

ObjectMapper solver = new ObjectMapper();

Objectabc = solver.readValue(new File(filename), ABC.class);

I am able to access bird,but

Objectabc.animal.type prints null.

Please tell me how can i access type and breed or color.

Wilson
  • 11,339
  • 2
  • 29
  • 33
warrior
  • 29
  • 5
  • This is because you don't deserialize the property `type` as you use it to instantiate the right `Animal` subclass. So instead try to print: `Objectabc.animal.getClass().getName()`. – Mario Santini Jul 16 '16 at 09:47
  • Possible duplicate of: http://stackoverflow.com/questions/30362446/deserialize-json-with-jackson-into-polymorphic-types-a-complete-example-is-giv – Vladimir Vagaytsev Jul 16 '16 at 13:09

0 Answers0