1

I know a similar question has been posted, however, the answer didn't work for me.

I am using RestAssured. How do I convert my Response into a JSON object and then extract a field that is within the JSON array (in my case, inside the errors array)?

Response response = 
           given().
                contentType(ContentType.JSON).
                body(jsonAsMap).
           when().
                post("/customers").
           then().
                statusCode(400).extract().response();
   //get "code" field inside "errors".

When testing the request in Postman, I get this result:

{
  "uri": "/customers/",
  "query": null,
  "method": "POST",
  "contentType": "application/json",
  "status": 400,
  "statusMessage": "Bad Request",
  "errors": [
    {
      "field": "firstName",
      "code": "firstName.required", //need to extract this field
      "message": "firstName is required"
    }
  ]
}

What is the easiest way to achieve this?

Community
  • 1
  • 1
Helenesh
  • 3,999
  • 2
  • 21
  • 36

2 Answers2

2

You can use JsonPath to access the value and convert this into a Java type.

Something like this:

String errorCode = ...then().extract().jsonPath().getString( "errors[0].code" )
mszalbach
  • 10,612
  • 1
  • 41
  • 53
0

In addition to the above answer, here is an alternate solution:

String errCode = ...then().extract().path("errors[0].code");
Prashanth Sams
  • 19,677
  • 20
  • 102
  • 125