java - 使用带有 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检索数组的总数(例如从 ' {
' 到 ' ' 的数组)?}
- 如果我必须使用 ' ' as 检索
stateCountyCode
结果集的 'cmsContract
'HB2345
,我该怎么做?我希望看到值返回为111225
请建议。
使用的库——
org.json.JSONObject;
io.restassured.RestAssured;
io.restassured.response.Response;
io.restassured.specification.RequestSpecification;
解决方案
您可以使用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
值。
希望能帮助到你!
推荐阅读
- javascript - 如何在 Javascript 中动态访问导入的函数?
- azure-devops - Azure DevOps 用户管理
- docker - 无法从 MacOS 中的主机访问 tezos 节点(在 Docker 中)
- java - 用列表转换对象
到不可变列表 - python - 关于自动化无聊的东西的问题:第 4 章
- python - Scipy: signal.detrend (type='constant' ) 究竟做了什么时间序列数据集,我可以在 python 中反转 signal.detrend 吗?
- elasticsearch - 如何将我的输入语句转换为 json 以将其作为输出参数传递?
- hl7-fhir - 将批量数据发送到 Azure FHIR 服务器
- c# - Microsoft 如何从 DLL 的元数据中隐藏 C# 内部类?
- regex - 正则表达式在拆分所有大写字母时仅找到 1 个匹配项