微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Java:使用json -SpringBoot中的“​​ @class”将json反序列化为其余模板中的对象

如何解决Java:使用json -SpringBoot中的“​​ @class”将json反序列化为其余模板中的对象

@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  
{

}

并配置您的解串器

    ObjectMapper mapper = new ObjectMapper();  
    mapper.getDeserializationConfig().addMixInAnnotations(  
    Animal.class, AnimalMixIn.class);

由于您使用的春天启动,您可以查看以下博客文章,看你如何自定义ObjectMapper使用混入,自杰克逊对象映射器,尤其要注意混入方法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;

解决方法

我必须实例化一个类,该类使用@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。控制台中出现此错误。

无法读取JSON:无法构造“ MyPOJO”的实例,问题:抽象类型要么需要映射到具体类型,要么具有自定义反序列化器,要么被其他类型信息实例化

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。