2016-12-15 26 views
1

我回JSON是一個匿名數組,看起來像這樣:如何在數組響應中查找特定條目?

[ 
    "name" : "John", 
    "age" : 26, 
    "likes" : "Ice Cream" 
], 
[ 
    "name" : "Jake", 
    "age" : 26, 
    "likes" : "Pizza" 
] 

在此基礎上我想條目,其中年齡是26名和喜歡是「比薩」(所以「傑克」在這種情況下)。我怎麼做?

到目前爲止,我已經知道了這一點,但它只是明顯錯誤,因爲hasItem並不關注兩個項目是否在同一個集合中。此外,答覆只是給了我一切。

String name = given().contentType("application/json").when(). 
       get(base + "/persons"). 
       then(). 
       statusCode(200). 
       body("age", hasItem(26)). 
       body("likes", hasItem("Pizza")). 
       extract().response(); 

你會怎麼做?

+0

試着改變你的收益結構,以 [{ 「名」: 「約翰」, 「時代」:26, 「喜歡」: 「冰淇淋」 }, { 「名」: 「傑克」, 「時代」:26, 「喜歡」: 「比薩」 }] – Bindrid

+0

噢,對不起,那是真正的情況。我忘記了代碼中的大括號。儘管如此,仍然沒有消除找到正確條目的問題。 – Selbi

回答

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); 

我不是100%肯定,將工作,但像它會: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()); 
    } 
} 
相關問題