Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

331
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda