How to validate a list of values from the response using RestAssured

11,924

There is in-build method in rest assured which you can use to get all item of Array as List of map.

String key="book";//array key (as it mentioned in your Json)
Response response=//your API call which will return Json Object
List<Hash<String,Object>>booksList=response.jsonPath().getList(key);
//Now parse value from List
Hash<String,Object> firstBookDetails=booksList.get(0);// for first index
String author=(String)firstBookDetails.get("author");
Share:
11,924

Related videos on Youtube

Qaddaffi
Author by

Qaddaffi

Updated on June 04, 2022

Comments

  • Qaddaffi
    Qaddaffi almost 2 years

    Could someone please me understand how to validate a list of items from the response. Say the response looks something like below,

    {  
       "store":{  
          "book":[  
             {  
                "author":"Nigel Rees",
                "category":"reference",
                "price":8.95,
                "title":"Sayings of the Century"
             },
             {  
                "author":"Evelyn Waugh",
                "category":"fiction",
                "price":12.99,
                "title":"Sword of Honour"
             },
             {  
                "author":"Herman Melville",
                "category":"fiction",
                "isbn":"0-553-21311-3",
                "price":8.99,
                "title":"Moby Dick"
             },
             {  
                "author":"J. R. R. Tolkien",
                "category":"fiction",
                "isbn":"0-395-19395-8",
                "price":22.99,
                "title":"The Lord of the Rings"
             }
          ]
       }
    }
    

    The element Book has four lists under it with different data, now if I want to validate the author name and the price sequentially (in a loop for instance) how can I achieve that..?

    I usually convert the response into a Json document and then validate, but in this case, if I use the Json path "Store.book.author", out of the four lists from the response, which list would it refer to..? That's where my confusion is.

    • Ben Kauer
      Ben Kauer about 6 years
      These are not four lists, these are four objects in an array. store.book[0].author refers to the author of the first item, store.book[1].author refers to the author of the second item and so on.
    • Qaddaffi
      Qaddaffi about 6 years
      Thank you for the answer. But in case if the response contains only the array of objects (not under store or book), how should I access it..? ex, { "author":"Nigel Rees", "category":"reference", "price":8.95, "title":"Sayings of the Century" }, { "author":"Evelyn Waugh", "category":"fiction", "price":12.99, "title":"Sword of Honour" }
    • Qaddaffi
      Qaddaffi about 6 years
      Got it. Used [0].author and so on to access it.
  • Qaddaffi
    Qaddaffi about 6 years
    Thank you, this does the job even more efficiently.