而不是像这样获取根级别:
List<String> jresponse = response.jsonPath().getList("$");
可以直接获取ID:
List<String> ids = path.getList("id");
然后,您可以使用 foreach 循环,而不是像这样使用索引:
List<String> ids = path.getList("id");
for (String id : ids) {
if (id.equals("1")) {
//do something
} else {
//do something else
}
}
EDIT:
最好的方法(可能)是创建表示 JSON 的对象。
为了做到这一点,我们必须了解 JSON 包含什么。到目前为止,您已经有了包含 JSON 对象的 JSON 数组。每个 JSON 对象包含id
and applicationId
。为了将此 JSON 解析为 Java 类,我们必须创建一个类。我们就这样称呼它吧Identity
。你可以随意称呼它。
public class Identity {
public String id;
public String applicationId;
}
以上是JSON Object的表示。字段名称是 JSON 中的确切名称。标识符应该是公开的。
现在,要将 JSON 解析为 Java 类,我们可以使用JsonPath
像这样:
Identity[] identities = path.getObject("$", Identity[].class);
然后,我们迭代数组以获得我们想要的:
for (Identity identity : identities) {
if (identity.id.equals("1")) {
System.out.println(identity.applicationId);
}
}
在此基础上,您可以创建一个完整的方法,而不仅仅是打印applicationId
像这样:
private static String getApplicationId(String id, Identity[] identities) {
for (Identity identity : identities) {
if (identity.id.equals(id)) {
return identity.applicationId;
}
}
throw new NoSuchElementException("Cannot find applicationId for id: " + id);
}
另一个编辑:
为了使用foreach
并得到applicationID
基于id
你需要使用getList
方法,但方式不同。
List<HashMap<String, String>> responseMap = response.jsonPath().getList("$");
在上面的代码中,我们获取了 JSON 数组中的 JSON 对象列表。
HashMap 中的每个元素都是一个 JSON 对象。字符串是这样的属性id
and applicationId
第二个String
是每个属性的值。
现在,我们可以使用foreach
像这样循环以获得所需的结果:
private static String getApplicationIdBasedOnId(Response response, String id) {
List<HashMap<String, String>> responseMap = response.jsonPath().getList("$");
for (HashMap<String, String> singleObject : responseMap) {
if (singleObject.get("id").equals(id)) {
return singleObject.get("applicationId");
}
}
throw new NoSuchElementException("Cannot find applicationId for id: " + id);
}