how to find the number of response object in json

2.8k views Asked by At

I have a JSON response to validate. I am writing a test secario where I want to assert if the response contains the number of objects or not. JSON response:

{
  "Result": {
    "resultCode": "1000",
  },
  "ResultClient": {
    "responseCode": null,
    "statusCode": null
  },
  "creditCard": {
    "number": null
  }
}

I want to assert that the response has 3 objects. How to do that? The response obj dosn't have size() or count() so I am unable to understand the path to the solution.I am writting my tests in rest-assured .

TestResponse testResponse = given()
                .contentType("application/json; charset=UTF-8")
                .body(cTestRequest)
                .when()
                .post(uri)
                .as(TestResponse.class);

now how to assert the json contains the 3 obj and the parameters inside the objs?

1

There are 1 answers

0
Johan On BEST ANSWER

You can do something like this:

when().
       get("/x").
then().
       body("keySet().size()", is(3));

The reason is that the JSON object is treated as Groovy Map so you can invoke functions on it. keySet() returns all keys as a Set and size() returns the size of this Set.