I am not sure if this solution will be what you are looking for but you can definitely extract the first name based on the id.
Use JsonPath
library in Rest Assured
. You can either pass JSON as a String JsonPath.from("json string")
or you can get it from Response
like this:
JsonPath path = response.jsonPath();
Then, you can get data
array and iterate over its elements like this:
List<HashMap<String, Object>> data = path.getList("data");
for (HashMap<String, Object> singleObject : data) {
if (singleObject.get("id").equals(6)) {
System.out.println(singleObject.get("first_name"));
}
}
The above will print name "Tracey" to the console.
You can either work with this code or create a method to return parameter based on id like this:
private static String getFirstNameById(JsonPath path, int id) {
List<HashMap<String, Object>> data = path.getList("data");
for (HashMap<String, Object> singleObject : data) {
if (singleObject.get("id").equals(id)) {
return (String) singleObject.get("first_name");
}
}
throw new NoSuchElementException(String.format("Can't find first_name with id: %d", id));
}
Just to make sure you understand - each of the element in data
array is JSON Object. We collector all of the objects with method getList
. Each of the object is represented by HashMap
of String
and Object
because it contains different types. first_name
is String and id
is Integer, that's why we have to use HashMap of Objects
as second generic argument.
Then we iterate over the HashMap, comparing id
of each JSON Object to get desired results.
You can also use Java Stream
if you'd like. The same method would look like this:
List<HashMap<String, Object>> data = JsonPath.from(json).getList("data");
Optional<String> firstName = data.stream().filter(x -> x.get("id").equals(6)).map(x -> (String) x.get("first_name")).findFirst();
if (firstName.isPresent()) {
System.out.println(firstName.get());
}