我的返回JSON是一个匿名数组,如下所示:
@Override
public void onResponse(JSONArray response) {
.....
HashSet<Movie> set = new HashSet<Movie>();
set.add(movie);
.....
movieList.addAll(set);
}
基于此,我想获得年龄为26岁的条目名称,喜欢的是“Pizza”(在这种情况下为“Jake”)。我该怎么做?
到目前为止,我已经得到了这个,但它只是完全错误,因为hasItem不会查看这两个项目是否在同一个集合中。响应也简单地给了我一切。
[
"name" : "John",
"age" : 26,
"likes" : "Ice Cream"
],
[
"name" : "Jake",
"age" : 26,
"likes" : "Pizza"
]
你会怎么做?
答案 0 :(得分:0)
使用JsonPath,您可以尝试:
Response response = given().contentType("application/json").get(base + "/persons");
response.then().statusCode(200);
String name = JsonPath.with(response.getBody()).getString("$[?(@.age == 26 && @.likes eq 'Pizza')].name");
Assert.assertEquals("Jake", name);
我不是百分之百确定它会起作用,但类似的东西会:https://static.javadoc.io/com.jayway.restassured/rest-assured/1.4/com/jayway/restassured/path/json/JsonPath.html
如果没有JsonPath,您可以这样做:
Response response = given().contentType("application/json")get(base + "/persons");
response.then().statusCode(200);
List<Person> people = Arrays.asList(response.getBody().as(Person[].class));
Assert.assertTrue(!people.isEmpty());
for(Person person : people) {
if(person.getAge() == 26 && person.getLikes().equals("Pizza")) {
Assert.assertEquals("Jake", person.getName());
}
}