Using Rest Assured (io.restassured) in Java and have the following JSON response format
{
"products": [
{
"name": "toy1",
"price": 99
},
{
"name": "toy2",
"price": 88
},
{
"name": "toy3",
"price": 99
}
]
}
I'm trying to find if a specific product exist given it's name and price.
So the following result (or assert) is expected
name | price | isExist |
---|---|---|
toy1 | 99 | true |
toy2 | 99 | false |
toy2 | 88 | true |
sometoy | 99 | false |
I tried:
There are 2 solutions
Here's an example of 2nd one.
public static void main(String[] args) {
// Example JSON response
String jsonResponse = "{ \"products\": ["
+ "{ \"name\": \"toy1\", \"price\": 99 },"
+ "{ \"name\": \"toy2\", \"price\": 88 },"
+ "{ \"name\": \"toy3\", \"price\": 99 }"
+ "] }";
// Parse JSON response
JsonPath jsonPath = new JsonPath(jsonResponse);
// Check for product existence
System.out.println(doesProductExist("toy1", 99, jsonPath)); // true
System.out.println(doesProductExist("toy2", 99, jsonPath)); // false
System.out.println(doesProductExist("toy2", 88, jsonPath)); // true
System.out.println(doesProductExist("sometoy", 99, jsonPath)); // false
}
public static boolean doesProductExist(String name, int price, JsonPath jsonPath) {
List<Map<String, Object>> products = jsonPath.getList("products");
return products.stream()
.anyMatch(product -> name.equals(product.get("name")) && price == (int) product.get("price"));
}