0

我一直在尝试反序列化从此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对象是动态的,即其内容不是恒定的。

4

1 回答 1

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);
于 2018-03-14T14:37:49.707 回答