0

我试图从以下 JSON 响应中提取 JSON 对象的已故计数总和

https://api.covid19india.org/state_district_wise.json

上面的片段是 json

"Maharashtra": {
    "districtData": {
      "Ahmednagar": {
        "notes": "",
        "active": 4206,
        "confirmed": 275516,
        "migratedother": 1,
        "deceased": 5565,
        "recovered": 265744,
        "delta": {
          "confirmed": 559,
          "deceased": 4,
          "recovered": 0
        }
      },

我想从马哈拉施特拉邦找到死者的总和。我知道我们可以在 JSONArray 上使用 collect,但这里是 JSONObject。我尝试了以下但无济于事

int value=jsonPath.get("Maharashtra.districtData.collect{it.deceased}.sum()");
4

1 回答 1

1

对象中有 2 个deceased键,我假设您只想要deceased外部对象中的 。到目前为止我得到的最简单的解决方案。

@Test
void name3() {
    Response res = RestAssured.given()
            .get("https://api.covid19india.org/state_district_wise.json");
    Map<String, ?> data = res.jsonPath().getMap("Maharashtra.districtData");
    Set<String> keys = data.keySet();
    int sum = keys.stream()
            .mapToInt(key ->
               JsonPath.read(res.asString(), String.format("$.Maharashtra.districtData.[\"%s\"].deceased", key)))
            .sum();
    System.out.println(sum); //126851
}

如果您不想使用 Java8 流。

int sum = 0;
for (String key : keys) {
    int deceased = JsonPath.read(res.asString(), String.format("$.Maharashtra.districtData.[\"%s\"].deceased", key));
    sum += deceased;
}

我使用 JsonPath (com.jayway.jsonpath.JsonPath)

pom.xml

<dependency>
    <groupId>com.jayway.jsonpath</groupId>
    <artifactId>json-path</artifactId>
    <version>2.6.0</version>
</dependency>

更新

我想出了另一个解决方案,即使用映射 POJO。

@Test
void name4() {
    Response res = RestAssured.given()
            .get("https://api.covid19india.org/state_district_wise.json");

    Configuration configuration = Configuration.builder()
            .jsonProvider(new JacksonJsonProvider())
            .mappingProvider(new JacksonMappingProvider())
            .build();

    List<DistrictData> data = JsonPath.using(configuration).parse(res.asString())
            .read("$.Maharashtra.districtData.*", new TypeRef<>() {});

    int sum = data.stream().mapToInt(DistrictData::getDeceased).sum();
    System.out.println(sum); //126851
}

POJO

import lombok.Data;
import java.util.Map;

@Data
public class DistrictData {
    private String notes;
    private int active;
    private int confirmed;
    private int migratedother;
    private int deceased;
    private int recovered;
    private Map<String, Object> delta;
}
于 2021-07-18T02:47:46.183 回答