Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

326
Vistas
Why does Jackson ignore in-class annotations but respect mix-in annotations?

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?

over 4 years ago · Santiago Trujillo
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda