Search code examples
javaspringjsonpathrest-assured-jsonpath

Rest Assured verifying JSON list of key/value pairs


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:

  • converting the JSON into a list of maps, but the overall solution was really messy
  • found a package that would be convenient and solve my problem, but there's restrictions preventing me from using it
  • considered flattening it, but that won't work since there would be key clashes

Solution

  • There are 2 solutions

    1. Create a POJO class for the sample JSON (leverage online json to pojo converters - https://json2csharp.com/code-converters/json-to-pojo)
    2. If you don't want to create extra POJO class, you can go ahead with io.restassured.path.json.JsonPath.

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