I use the swagger-codegen-maven-plugin version 2.2.2 to generate Java classes for a REST API. The API uses polymorphism and Swagger provides corresponding annotations:
@JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
include = JsonTypeInfo.As.PROPERTY,
property = "type",
visible = true )
@JsonSubTypes({
@Type(value = Cat.class, name = "Cat"),
@Type(value = Dog.class, name = "Dog") })
public class Pet{
@JsonProperty("type")
private String type = null;
// getter and setters
}
Now I use a Jackson ObjectMapper to parse the incoming JSON string. I use the Jackson that comes with the 1.5.2.RELEASE of spring-boot-starter-parent:
ObjectMapper mapper = new ObjectMapper();
String body = "{ \"pet\": { \"type\": \"Dog\" } }";
Content content = mapper.readValue(body, Content.Class);
However, this fails. Jackson ignores the annotations and maps everything to Pet instead of Dog:
Dog dog = (Dog) content.getPet(); // -> ClassCastException
As a workaround, I added mix-in annotations that do nothing more than the original annotations. The only difference is that they reside in a separate class:
@JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
include = JsonTypeInfo.As.PROPERTY,
property = "type",
visible = true)
@JsonSubTypes({
@Type(value = Cat.class, name = "Cat"),
@Type(value = Dog.class, name = "Dog")})
public class PetAnnotations {
}
Now this works:
// like above
mapper.addMixInAnnotations(Pet.class, PetAnnotations.class);
Content content = mapper.readValue(body, Content.Class);
Dog dog = (Dog) content.getPet(); // -> works!
Any ideas why Jackson ignores the in-class annotations but respects the annotations I explicitly hand in as mix-ins?