如何在 JSON 对象的 restassured 中使用 gpath sum() 获取值的总和

How to get the summation of values using gpath sum() in restassured on JSON Object

我试图从以下 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()");

对象中有 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;
}