我必须实例化一个类,该类使用@class中的信息从JSON扩展了抽象类,如下所示.
"name": {
"health": "xxx",
"animal": {
"_class": "com.example.Dog",
"height" : "20"
"color" : "white"
}
},
这里的抽象类是动物,而狗则扩展了动物类.因此,使用@class中的信息,我们可以直接实例化dog吗.这也是我在restTemplate中得到的响应
ResponseEntity<List<SomeListName>> response = restTemplate.exchange("http://10.150.15.172:8080/agencies", HttpMethod.GET, request, responseType);
执行此行时,将出现以下错误.
由于POJO类是自动生成的,因此无法使用@JsonTypeInfo之类的注释
我正在使用Spring Boot和Maven.
控制台中出现此错误.
Could not read JSON: Can not construct instance of “MyPOJO”, problem: abstract types either need to be mapped to concrete types, have custom deserializer, or be instantiated with additional type information
解决方法:
通过遵循MixIn’s,可以使用@JsonTypeInfo批注,而不考虑生成类的事实.
“mix-in annotations are”: a way to associate annotations with
classes, without modifying (target) classes themselves.That is, you can:
Define that annotations of a mix-in class (or interface) will be used
with a target class (or interface) such that it appears as if the
target class had all annotations that the mix-in class has (for
purposes of configuring serialization / deserialization)
因此,您可以编写AnimalMixIn类,例如
@JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
include = JsonTypeInfo.As.PROPERTY,
property = "_class")
@JsonSubTypes({
@Type(value = Cat.class, name = "com.example.Cat"),
@Type(value = Dog.class, name = "com.example.Dog") })
abstract class AnimalMixIn
{
}
并配置您的解串器
ObjectMapper mapper = new ObjectMapper();
mapper.getDeserializationConfig().addMixInAnnotations(
Animal.class, AnimalMixIn.class);
由于您使用的是Spring Boot,因此可以查看以下博客文章,以了解如何自定义ObjectMapper以使用MixIns,Customizing the Jackson Object Mapper,尤其要注意Jackson2ObjectMapperBuilder的mixIn方法
在RestTemplate中使用自定义的ObjectMapper应该通过转换器进行设置,例如
RestTemplate restTemplate = new RestTemplate();
List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
MappingJackson2HttpMessageConverter jsonMessageConverter = new MappingJackson2HttpMessageConverter();
jsonMessageConverter.setObjectMapper(objectMapper);
messageConverters.add(jsonMessageConverter);
restTemplate.setMessageConverters(messageConverters);
return restTemplate;