1

如何让 Jackson 使用子接口(下面的 Cat)而不是子类(Lion)来序列化类型?

父界面动物

@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();
}

子接口猫

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

子类狮子

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

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

测试用例

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

当前输出是 {"type": "Lion"}

所需的输出是 {"type":"Cat"}

4

0 回答 0