如何在 parent class 中指定类型时在 Jackson 中不使用类型 属性 进行 child class 反序列化

how to make child class deserialize without type property in Jackson while type specified in parent class

我有一项服务接收我的 parent 接口作为输入,以便接收不同的类型作为输入。 接口定义如下:

@JsonTypeInfo(use=JsonTypeInfo.Id.NAME, include=JsonTypeInfo.As.PROPERTY)
@JsonSubTypes({
    @JsonSubTypes.Type(value = Person.class, name = "person"),
    @JsonSubTypes.Type(value = Employee.class , name = "employee")
})
public interface TestInterface {
}

我有一个获取 TestInterface 的服务,如下所示:

@RequestMapping(value="/convert", method = RequestMethod.POST)
@ResponseBody
public Person test(@RequestBody TestInterface object){}

此服务必须像下面那样获得 json,并且仅适用于类型为 属性:

的文件
 {"@type":"person","name":null,"family":"fami"}

问题是当我有一个服务直接接收 child class 而我不想指定类型 属性.

@RequestMapping(value="/convertPerson", method = RequestMethod.POST)
@ResponseBody
public Person test(@RequestBody Person object){}

在此示例中,当我不发送类型 属性 时,我得到(缺少类型 ID 属性)异常。有没有办法让它在没有类型 ID 的情况下工作? 我已经尝试了以下配置,但没有解决问题:

spring.jackson.deserialization.fail-on-missing-external-type-id-property=false

通过将@JsonTypeInfo(use = JsonTypeInfo.Id.NONE) 放在child class 之上解决了这个问题。使用此注释 child class 可以在没有类型的情况下独立工作,并且 parent 接口也可以与类型一起正常工作。

@JsonTypeInfo(use = JsonTypeInfo.Id.NONE)
public class Person implements TestInterface{
}