我一直在尝试反序列化从this API收到的数据:
{
"result": "success",
"timestamp": 1521038012878,
"data": {
"GB": 14,
"DE": 2,
"US": 2
},
"totalIsPublic": true,
"advanced": false,
"totalDownloads": {
"GB": 14,
"DE": 2,
"US": 2
}
}
这是POJO课程:
public class BintrayDownloadCounts {
private List<Integer> totalDownloads = new ArrayList<>();
@JsonProperty("totalDownloads")
public List<Integer> getTotalDownloads() {
return totalDownloads;
}
public void setTotalDownloads(List<Integer> totalDownloads) {
this.totalDownloads = totalDownloads;
}
}
当我尝试使用:
进行反序列化时downloadCounts = mapper.readValue(json, BintrayDownloadCounts.class);
我收到此错误:
com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.lang.Integer out of START_OBJECT token
我看到很多问题包含此错误,但我无法找到针对此特定用例的解决方案。可以注意到totalDownloads
对象是动态的,即其内容不是恒定的。
答案 0 :(得分:1)
totalDownloads
属性不是数组,因此无法映射到List<Integer>
。请改用Map<String, Integer>
并确保告诉Jackson忽略未映射的属性以避免映射错误:
@JsonIgnoreProperties(ignoreUnknown = true)
public class BintrayDownloadCounts {
@JsonProperty("totalDownloads")
private Map<String, Integer> totalDownloads;
public Map<String, Integer> getTotalDownloads() {
return totalDownloads;
}
public void setTotalDownloads(Map<String, Integer> totalDownloads) {
this.totalDownloads = totalDownloads;
}
}
然后你很高兴:
ObjectMapper mapper = new ObjectMapper();
BintrayDownloadCounts downloadCounts = mapper.readValue(json, BintrayDownloadCounts.class);