RestAssured 使用 foreach 循环解析 Json 数组响应

2024-04-09

我收到 RestAssured 的回复,它是一个 JsonArray,看起来类似于下面的代码

[{ "id": "1", "applicationId": "ABC" }, { "id": "2", "applicationId": "CDE" }, { "id": "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
            }
        }

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);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

RestAssured 使用 foreach 循环解析 Json 数组响应 的相关文章

随机推荐