首页 > 解决方案 > 使用带有 JAVA 和 Selenium 的 REST ASSURED 计算数组的数量并访问 JSON 响应中的特定数组

问题描述

我正在使用 Rest Assured API 和 Java 通过我的 selenium 自动化程序执行 POST 调用操作。IO 得到如下所述的响应-

{
    "cmsContract": "HA1123",
    "groupId": "12345",
    "siteId": "4444-AP",
    "stateCountyCode": "7978790"
  },
  {
    "cmsContract": "HB2345",
    "groupId": "9876",
    "siteId": "8888-DK",
    "stateCountyCode": "111225"
  }

响应中有大约 1000 个或更多 JSON 对象。而且他们没有响应的标识符,例如“名称”或“合同信息”

我的查询: 1. 如何使用与 JAVA 和 selenium 结合的 Rest Assured APIs检索数组的总数(例如从 ' {' 到 ' ' 的数组)?}

  1. 如果我必须使用 ' ' as 检索stateCountyCode结果集的 ' cmsContract' HB2345,我该怎么做?我希望看到值返回为 111225

请建议。

使用的库——

org.json.JSONObject;
io.restassured.RestAssured;
io.restassured.response.Response;
io.restassured.specification.RequestSpecification;

标签: javajsonrest-assured

解决方案


您可以使用JsonPath来解析 JSON 响应。基本上,您可以JsonPath从字符串、文件或响应中获取类。

从字符串:

JsonPath path = JsonPath.from("json string");

从文件:

JsonPath path = JsonPath.from(new File("path to file"));

来自回应:

Response response; //we get it from RestAssured by calling POST/GET etc
JsonPath path = response.body().jsonPath();

为了获取 JSON 结构中的任何元素,就像您的情况一样,我们必须将其提供给JsonPath. 示例 JSON:

{ 
    "data": [
      {
         "name": "test"
      },
      {
         "name": "test1"
      }
    ]
}

为了访问数组中的元素,我们必须知道它的所有父元素。结构如下所示:

path.get("parent.child.anotherChild");

数组变得更加棘手,因为我们必须使用索引。上"data"例中的 是一个数组。为了访问test1,我们将使用:

path.get("data[1].name"); //second element in the array

但这是标准方法。JsonPath 是一个更强大的库。

最后,回答你的问题。我们如何获得数组中 JSON 对象的计数?

List<HashMap<String, Object>> jsonObjects = path.getList("data"); //You have to provide name of the Array's parent. In my case, it's `data`

在上面的 HashMap 列表中,我们在 JSON 数组中有所有 JSON 对象。因此,您可以使用多种方法来计算元素。

要计算有多少 JSON 对象,您可以简单地使用 List 的方法:

jsonObjects.size();

使用相同的列表,我们可以获得cmsContract价值,如您的示例。我们寻找价值HB2345

标准for循环。如果你知道怎么做,你可以使用 Streams。

public String getStateCountryCodeFromCmsContract(String cmsContractValue) {
    for (HashMap<String, Object> singleJsonObject : jsonObjects) {
        String cmsContract = (String) singleJsonObject.get("cmsContract");
        if (cmsContract.equals(cmsContractValue)) {
            return (String) singleJsonObject.get("stateCountyCode");
        }
    }
}

我们遍历每个 JSON 对象,检查cmsContract元素的值,如果它等于所需的值 - 返回stateCountryCode值。

希望能帮助到你!


推荐阅读