如何让Jackson使用子接口(下面的Cat)而不是子类(Lion)来序列化类型?
父接口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();
}
子类狮子
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));
目前的输出是{"类型":"狮子"}
所需的输出是{"类型":" Cat"}