Java 如何使用JsonSubTypes对属性使用动态反序列化?
我有一个类Java 如何使用JsonSubTypes对属性使用动态反序列化?,java,json,spring,jackson,deserialization,Java,Json,Spring,Jackson,Deserialization,我有一个类Food,需要用作反序列化类 公共级食品{ 私有VegetableConfiguration VegetableConfiguration; 私人色彩; // ... //能手/二传手 } 公共接口VegetableConfiguration{ // ... } 公共类PotatoConfiguration实现了VegetableConfiguration{ // ... } public类配置实现了VegetableConfiguration{ // ... } public
Food
,需要用作反序列化类
公共级食品{
私有VegetableConfiguration VegetableConfiguration;
私人色彩;
// ...
//能手/二传手
}
公共接口VegetableConfiguration{
// ...
}
公共类PotatoConfiguration实现了VegetableConfiguration{
// ...
}
public类配置实现了VegetableConfiguration{
// ...
}
public类PepperConfiguration实现了VegetableConfiguration{
// ...
}
公共枚举颜色{
棕色、橙色、红色
}
我需要根据从响应中获得的Color
选择一个实现VegetableConfiguration
我正在尝试使用JsonTypeInfo
表单Jackson。根据JavaDoc,它可以用于属性
公共级食品{
@JsonTypeInfo(
use=JsonTypeInfo.Id.NAME,
property=“color”)
@JsonSubTypes({
@JsonSubTypes.Type(value=PotatoConfiguration.class,name=“BROWN”),
@JsonSubTypes.Type(value=configuration.class,name=“ORANGE”),
@JsonSubTypes.Type(value=PepperConfiguration.class,name=“RED”),
})
私有VegetableConfiguration VegetableConfiguration;
私人色彩;
// ...
//能手/二传手
}
但它失败了,出现以下错误
org.springframework.web.client.RestClientException: Error while extracting response for type [Food] and content type [application/json;charset=UTF-8]; nested exception is org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Missing type id when trying to resolve subtype of [simple type, class VegetableConfiguration]: missing type id property 'color' (for POJO property 'vegetableConfiguration'); nested exception is com.fasterxml.jackson.databind.exc.InvalidTypeIdException: Missing type id when trying to resolve subtype of [simple type, class VegetableConfiguration]: missing type id property 'color' (for POJO property 'vegetableConfiguration')
如何根据color
选择反序列化的VegetableConfiguration
实现
最好不实现自定义反序列化程序。您需要使用。从文件:
包含机制类似于属性
,,但属性是
在层次结构中包括一个更高的级别,即在
与要键入的JSON对象的级别相同。请注意,此选项只能是
用于属性,不用于类型(类)。试着用它来
类将导致基本属性的包含策略
另见:
Jackson
?尝试将include=JsonTypeInfo.As.EXTERNAL_属性
配置添加到@JsonTypeInfo
@MichałZiober中,直到成功!请随意写一个答案。我使用2.9.8