'serializing object to JSON using @JsonSubTypes and openAPI SpringCodegen

I will use the pet store example to demonstrate the issue. I have a store with collection of pets, and pets can be different type.

First a created an API contact with open API

Generated model object for store

public class Store   {
     @JsonProperty("name")
      private String name;
      
      @JsonProperty("pets")
      @Valid
      private List<Pet> pets = new ArrayList<>();
      
      getters/setters
      }

Generated Pet model

javax.annotation.Generated(value = "org.openapitools.codegen.languages.SpringCodegen", date = "2022-05-11T18:58:23.567613300-04:00")

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXISTING_PROPERTY, property = "type", visible = true)
@JsonSubTypes({
  @JsonSubTypes.Type(value = Cat.class, name = "cat"),
  @JsonSubTypes.Type(value = Dog.class, name = "dog"),
  @JsonSubTypes.Type(value = Pig.class, name = "pig"),
})

public class Pet   {
  /**
   * Gets or Sets evidenceType
   */
  public enum TypeEnum {
    CAT("cat"),
    
    DOG("dog"),
    
    PIG("pig");
    }
}

Generated Type classes

public class Cat extends Pet{
}
public class Dog extends Pet{
}
public class Pig extends Pet{
}

Problem:

when I create a pet object with collection of multiple types i am getting the following an InvalidTypeIdException exception:

Caused by: com.fasterxml.jackson.databind.exc.InvalidTypeIdException: Could not resolve type id 'dog' as a subtype of Cat: Class Dog not subtype of Cat

.. But when a create a Store with only one type of pet, object sterilized without any issue

tried register subtype using ObjectMapper.registerSubtype.. didn't work

De-serializing JSON to polymorphic object model using Spring and JsonTypeInfo annotation



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source