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