我需要针对以下 json 响应正文中“字段”(即“同意”、“失败计数”)下的值进行提取和/或断言:
{
"next": null,
"previous": null,
"results": [
{
"huid": "be7d-794186bda2d3",
"name": null,
"language": "eng",
"arns": [
"doodle:123456"
],
"groups": [],
"fields": {
"consent": "TRUE",
"failure_count": 2,
"timestamp": "2020-04-17T12:04:04.978887Z",
"registration_type": "normal"
},
"blocked": false,
"stopped": false,
"created_on": "2020-04-17T12:04:04.978887Z",
"modified_on": "2020-04-17T12:04:05.692949Z"
}
]
最佳答案
如果您希望结果为数组,您可以创建 pojo 类。例如:
public class ExampleResponse {
private Object next;
private Object previous;
private Result[] results;
//add getters and setters
public class Result {
private String huid;
private String name;
//add getters and setters
}
}
然后将您的 json 响应转换为 java 对象
ExampleResponse pojo = given()
.when().get(endpoint)
.then().extract().body().as(ExampleResponse.class);
在此操作之后,您可以提取和/或断言任何字段。例如:
...
results[0].isBlocked();
...
您也可以尝试使用路径方法提取字段值:
...
given()
.when().get(endpoint)
.path("results[0].arns[0]");
...
given()
.when().get(endpoint)
.path("results[0].fields.timestamp");
...
如果你期望通常的 json(没有结果作为数组),你可以使用这个方法:
//assert value
given()
.when().get(endpoint)
.then()
.assertThat()
.body("result.name", equalTo(someName));
//assert response has or not parameter
given()
.when().get(endpoint)
.then()
.body("results", hasKey("name"))
.body("results", not(hasKey("name")));
关于 usage page 的更多示例.和 this description也可以有用! 希望对您有所帮助!
关于rest-assured - 从 Rest Assured 响应中提取嵌套值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61318098/