我收到了来自 RestAssured 的回复,这是一个 JsonArray 看起来类似于下面的代码
[{
“编号”:“1”,
"applicationId": "ABC"
}, {
“编号”:“2”,
“applicationId”:“CDE”
}, {
“编号”:“3”,
“applicationId”:“XYZ”
}]
我使用代码从第一个 Json 元素获取“id”
List<String> jresponse = response.jsonPath().getList("$");
for (int i = 0; i < jsonResponse.size(); i++) {
String id = response.jsonPath().getString("id[" + i + "]");
if(id.equals("1"){
do something
}
else {
something else
}
}
有没有办法在上面的代码中使用 foreach 代替 for?
最佳答案
而不是像这样获取根级别:
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
}
}
编辑:
最好的方法(可能)是创建代表 JSON 的对象。
为此,我们必须了解 JSON 包含的内容。到目前为止,您已经拥有包含 JSON 对象的 JSON 数组。每个 JSON 对象包含 id
和 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
并根据 id
获取 applicationID
你需要使用 getList
方法但是在不同的方式。
List<HashMap<String, String>> responseMap = response.jsonPath().getList("$");
在上面的代码中,我们获取了 JSON 数组中的 JSON 对象列表。
HashMap 中的每个元素都是一个 JSON 对象。字符串是 id
和 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);
}
关于rest-assured - RestAssured 使用 foreach 循环解析 Json 数组响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56913639/