Java:使用json -SpringBoot中的"​​@class"将json反序列化为rest模板中的object

Kar*_*ala 1 java jackson deserialization resttemplate spring-boot

我必须实例化一个类,它使用@class中的信息从JSON扩展抽象类,如下所示.

"name": {
  "health": "xxx",
  "animal": {
    "_class": "com.example.Dog",
    "height" : "20"
    "color" : "white"
  }
},
Run Code Online (Sandbox Code Playgroud)

这里抽象类是动物,狗延伸动物类.因此,使用@class中的信息,我们可以直接实例化狗.这也是我在restTemplate中得到的回应

ResponseEntity<List<SomeListName>> response = restTemplate.exchange("http://10.150.15.172:8080/agencies", HttpMethod.GET, request, responseType);
Run Code Online (Sandbox Code Playgroud)

执行此行时会出现以下错误.由于POJO类是自动生成的,我不能使用像@JsonTypeInfo这样的注释

我正在使用Spring boot和maven.此错误将在控制台中出现.

无法读取JSON:无法构造"MyPOJO"的实例,问题:抽象类型需要映射到具体类型,具有自定义反序列化器,或者使用其他类型信息进行实例化

Mas*_*ave 5

@JsonTypeInfo通过遵循MixIn,您可以使用注释,无论生成类的事实如何

"混合注释是":一种将注释与类相关联的方法,而无需修改(目标)类本身.

也就是说,您可以:

定义混合类(或接口)的注释将与目标类(或接口)一起使用,使得它看起来好像目标类具有混合类具有的所有注释(用于配置序列化/反序列化)

所以你可以写你的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  
{  

}  
Run Code Online (Sandbox Code Playgroud)

并配置您的反序列化程序

    ObjectMapper mapper = new ObjectMapper();  
    mapper.getDeserializationConfig().addMixInAnnotations(  
    Animal.class, AnimalMixIn.class);
Run Code Online (Sandbox Code Playgroud)

由于您使用的是Spring Boot,因此您可以查看以下博文,了解如何自定义ObjectMapper以使用MixIns,自定义Jackson Object Mapper,特别注意mixIn方法Jackson2ObjectMapperBuilder

使用自定义ObjectMapper内部RestTemplate应该通过转换器设置,如

    RestTemplate restTemplate = new RestTemplate();
    List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
    MappingJackson2HttpMessageConverter jsonMessageConverter = new MappingJackson2HttpMessageConverter();
    jsonMessageConverter.setObjectMapper(objectMapper);
    messageConverters.add(jsonMessageConverter);
    restTemplate.setMessageConverters(messageConverters);
    return restTemplate;
Run Code Online (Sandbox Code Playgroud)