How to serialize JsonSubType with child interface instead of subclass?

514 views Asked by At

How can I get Jackson to serialize the type using the child interface (Cat below) instead of the subclass (Lion)?

Parent interface Animal

@JsonTypeInfo(
    use = JsonTypeInfo.Id.NAME,
    include = JsonTypeInfo.As.PROPERTY,
    property = "type"
)
@JsonSubTypes({
    @JsonSubTypes.Type(Cat.class),
    @JsonSubTypes.Type(Dog.class)
})
public interface Animal {
  String getType();
}

Child interface Cat

@JsonDeserialize(
    as = Lion.class
)
public interface Cat extends Animal {
    String getType();
}

Subclass Lion

public class Lion implements Cat {
    @JsonProperty("type")
    private String type = null;

    @JsonProperty("type")
    public String getType() {
        return this.type;
    }
}

Test case

Cat cat = new Lion();
ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.writeValueAsString(cat));

The current output is {"type": "Lion"}

The desired output is {"type":"Cat"}

0

There are 0 answers