Deserializing JSON to an abstract class, interface, or to inherited objects in Spring Boot Webclient


@JsonTypeInfo and @JsonSubTypes annotations.

First, you need to ensure that your classes are properly annotated for serialization and deserialization. You can use the @JsonTypeInfo and @JsonSubTypes annotations to specify the type hierarchy of your objects
@JsonTypeInfo(
  use = JsonTypeInfo.Id.NAME,
  include = JsonTypeInfo.As.PROPERTY,
  property = "type")
@JsonSubTypes({
  @JsonSubTypes.Type(value = Cat.class, name = "cat"),
  @JsonSubTypes.Type(value = Dog.class, name = "dog")
})
public abstract class Animal {
  String type;
  // ...
}
{
  "animalList": [
    {
      "type": "cat",

       // ... some other properties

    },
    {
      "type": "dog"

      // ... some other properties

    }
  ]
}

@JsonSubTypes with not matching any conditions and return as null

If you have a JSON object that does not match any of the defined subtypes, you can configure Jackson to return null for the deserialized object. You can do this by using the @JsonSubTypes.Type annotation with a default value:
@JsonTypeInfo(
  use = JsonTypeInfo.Id.NAME,
  include = JsonTypeInfo.As.PROPERTY,
  property = "type")
@JsonSubTypes({
  @JsonSubTypes.Type(value = Cat.class, name = "cat"),
  @JsonSubTypes.Type(value = Dog.class, name = "dog"),
  @JsonSubTypes.Type(value = Void.class, name = "")
})
public abstract class Animal {

  String type;
  // ...
}