Home > Software engineering >  How get size of an array in json response? rest assured API, JAVA
How get size of an array in json response? rest assured API, JAVA

Time:11-16

I found a lot of topics with this question on this portal, but anyway I was not able to achieve what I need. I keep getting the next exception: java.lang.IllegalArgumentException: The parameter "roles" was used but not defined. Define parameters using the JsonPath.params(...) function .

Partially my code:

import static io.restassured.RestAssured.given;
import io.restassured.RestAssured;
import io.restassured.path.json.JsonPath;
import io.restassured.response.Response;


String baseURItest = RestAssured.baseURI = "http://testapi.test.com/testapps");
Response response;
response = given().when().get("/getAllRoles?token=token");
countRoles=response.body().path("$..roles.size()");
System.out.println(countRoles);

console output:

> java.lang.IllegalArgumentException: The parameter "roles" was used but
> not defined. Define parameters using the JsonPath.params(...) function

and json body response:

{
    "Message": "",
    "Status": 200,
    "Data": {
        "errors": [],
        "roles": [
            {
                "ROLEKEY": "1",
                "ROLEID": 1,
                "ROLENAME": "name1",
                "ROLEDESCRIPTION": "1"
            },
            {
                "ROLEKEY": "2",
                "ROLEID": 2,
                "ROLENAME": "name2",
                "ROLEDESCRIPTION": "12"
            },
            {
                "ROLEKEY": "3",
                "ROLEID": 3,
                "ROLENAME": "name3",
                "ROLEDESCRIPTION": "x"
            }
        ]
    }
}

I also tried :

  JsonPath jsonPathValidator = response.jsonPath();
  System.out.println(jsonPathValidator.get("$..ROLEKEY").toString());

I would say I tried a lot of different ways that I found in google, but each time I will get the same error. Can someone please explain to me what am I missing here, please? Or what should I do? Thank you in advance for any help!

CodePudding user response:

Problem: You misunderstand JsonPath in Rest-Assured.

Note from Rest-Assured wiki.

Note that the "json path" syntax uses Groovy's GPath notation and is not to be confused with Jayway's JsonPath syntax.

Solution: you can choose one of two ways below:

  1. Use JsonPath jayway by adding this to pom.xml (or gradle.build)
<dependency>
    <groupId>com.jayway.jsonpath</groupId>
    <artifactId>json-path</artifactId>
    <version>2.6.0</version>
</dependency>
Response res = given().when().get("/getAllRoles?token=token");
JsonPath.read(res.asString(), "$..ROLEKEY");
  1. You can use JsonPath from Rest-Assured.
List<String> roles = response.jsonPath().getList("Data.roles.ROLEKEY");
System.out.println(roles);
//[1,2,3]
  • Related