Randall Brukman
Randall Brukman

Reputation: 31

Extracting nested value from Rest Assured response

I need to extract and/or assert against the values under "fields" (ie. "consent", "failure count") in the following json response body:

{
"next": null,
"previous": null,
"results": [
    {
        "huid": "be7d-794186bda2d3",
        "name": null,
        "language": "eng",
        "arns": [
            "doodle:123456"
        ],
        "groups": [],
        "fields": {
            "consent": "TRUE",
            "failure_count": 2,
            "timestamp": "2020-04-17T12:04:04.978887Z",
            "registration_type": "normal"
        },
        "blocked": false,
        "stopped": false,
        "created_on": "2020-04-17T12:04:04.978887Z",
        "modified_on": "2020-04-17T12:04:05.692949Z"
    }
]

}

Upvotes: 3

Views: 6789

Answers (2)

Rajesh Chaudhary
Rajesh Chaudhary

Reputation: 112

You can convert you response body to jsonpath. After converting to jsonpath you can use below code to get the value of "consent", "failure count".

JsonPath responseJsonPath = new JsonPath(jsonString) 
String consent = responseJsonPath.getString("results[0].fields.consent");
int failureCount = responseJsonPath.getInt("results[0].fields.failure_count");

I am considering you are getting ValidatableResponse from API. Please let me know if you face any problem.

Upvotes: 0

Akane
Akane

Reputation: 11

If you expect result as array you can create pojo class. For example:

public class ExampleResponse {
    private Object next;
    private Object previous;
    private Result[] results;

    //add getters and setters

    public class Result {
        private String huid;
        private String name;

        //add getters and setters
    }
}

and then transform your json response to java object

ExampleResponse pojo = given()
    .when().get(endpoint)
    .then().extract().body().as(ExampleResponse.class);

after this manipulation you can extract and/or assert any field. For example:

...
results[0].isBlocked();
...

Also you can try extract fields value using path method:

...
given()
    .when().get(endpoint)
    .path("results[0].arns[0]");

...

given()
    .when().get(endpoint)
    .path("results[0].fields.timestamp");
...

If you expected usual json (without results as array), you can use this methods:

//assert value
given()
    .when().get(endpoint)
    .then()
    .assertThat()
    .body("result.name", equalTo(someName));

//assert response has or not parameter
given()
    .when().get(endpoint)
    .then()
    .body("results", hasKey("name"))
    .body("results", not(hasKey("name")));

More examples on usage page. And this description can be useful too! Hope this help!

Upvotes: 1

Related Questions