【发布时间】: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