【问题标题】:Spring RestTemplate and JSON how to ignore empty Arrays deserialization?Spring RestTemplate 和 JSON 如何忽略空数组反序列化?
【发布时间】:2015-10-23 13:51:59
【问题描述】:

我目前正在使用带有 RestTemplate 的 Spring 4.1.6 来使用 JSON 格式的第三方 Web 服务,但我无法更改其行为。我正在使用 Jackson 数据绑定 v2.6.0。

问题: 有时服务会为成员返回一个 hashmap {member:{"key":"value",...}} 有时同一个成员只是一个空数组 {member: []}。所以我不能默认忽略这个属性。

有没有办法将反序列化配置为忽略空数组?我看到了一个 jackson 属性“WRITE_EMPTY_JSON_ARRAYS”,但我不太确定如何将它与我的 restTemplate 和 spring 配置一起使用。

还有其他可能性吗?使用@JsonXXX 注释的某种组合?我看到@JsonSerialize 可以在类级别使用,但我不喜欢为我的所有类编写一个反序列化器来处理这种情况(但是,如果没有其他方法,我当然会这样做)

说明服务行为的示例响应:

  • 使用哈希图响应 {"id":170,"categories":{"13":"caro"}}

  • 以相同成员的空数组响应 {"id":170,"categories":[]}

我的 RestTemplate 使用示例:

    BasicAuthRequestFactory requestFactory = new BasicAuthRequestFactory(httpClient);        
    restTemplate = new RestTemplate(requestFactory);
    Article a = restTemplate.getForObject(new URI("http://..."), Article.class);

错误:

 caused by: com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.util.LinkedHashMap out of START_ARRAY token
 at [Source: java.io.PushbackInputStream@4aa21f9d; line: 1, column: 1456] (through reference chain: ResponseArticleWrapper["data"]->Article["categories"])
 at com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:148)

我当前的注释类示例:

@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(Include.NON_NULL)
public class Article {  
    @JsonProperty("id")
    private Integer id;
    @JsonProperty("categories")  
    private Map<Integer,String> categories = new HashMap<Integer,String>();
}

提前感谢您提供任何提示和示例。

【问题讨论】:

    标签: arrays json spring deserialization resttemplate


    【解决方案1】:

    从 jackson-databind 2.5 开始,有DeserializationFeature 用于处理这种情况。它默认是关闭的,所以你需要在你的ObjectMapper中配置它:

    @Bean
    public ObjectMapper objectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(DeserializationFeature.ACCEPT_EMPTY_ARRAY_AS_NULL_OBJECT, true);
        return objectMapper;
    }
    

    您可以在此处查看RestTemplate 的自定义ObjectMapper 是如何配置的:How can we configure the internal Jackson mapper when using RestTemplate?

    完成配置后,您可以让 Spring 在您的班级中为您接线:

    @Autowired
    private RestOperations restTemplate;
    

    并使用提供的restTemplate 实例。

    【讨论】:

    • 谢谢,这看起来很有希望。只是如何在我的 RestTemplate 中注入 objectMapper?我无法从你的代码 sn-p 中得到它。
    • 编辑:为答案添加了额外的解释
    猜你喜欢
    • 2020-11-06
    • 2018-07-20
    • 2014-01-24
    • 1970-01-01
    • 2021-06-22
    • 1970-01-01
    • 2016-11-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多