'RestAssured - Get values from nested object using Groovy gson path

How to use rest assured to get the list of all the zips from the below below structure?

{
    "persons":[
        {
            "name": "",
            "age":"",
            "addresses": [
                {
                    "city": "..",
                    "zip": ".."
                }
            ]
        }
    ]
}

Expected result is List<String> which contains zip codes only using groovy gson path.



Solution 1:[1]

This would work:

import io.restassured.path.json.JsonPath;
...

List<List<String>> temp = JsonPath.from(res).getList("persons.addresses.zip");
List<String> zips = temp.stream().flatMap(List::stream).collect(Collectors.toList());
System.out.println(zips);
//[..]

Solution 2:[2]

You could use flatten() method to get the zip code:

List<String> zips =JsonPath.from(res).getList("persons.addresses.flatten().zip")

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 lucas-nguyen-17
Solution 2