Use JSONAssert on part of JSON with RESTAssured

2k Views Asked by At

I am able to retrieve JSON from a service using RESTAssured.

I would like to use the JSONPath capability to extract JSON and then compare it using JSONAssert.

Here's my example:

@Test
public void doAPITestExample() throws JSONException {
    // retrieve JSON from service
    Response response = RestAssured.given().get("http://localhost:8081/mockservice");
    response.then().assertThat().statusCode(200);

    String body = response.getBody().asString();
    System.out.println("Body:" + body);
    /*
        {"datetime": "2018-06-21 17:48:07.488384", "data": [{"foo": "bar"}, {"test": "this is test data"}]}
    */

    // able to compare entire body with JSONAssert, strict=false
    Object data = response.then().extract().path("data");
    System.out.println("Response data:");
    System.out.println(data.getClass()); // class java.util.ArrayList
    System.out.println(data.toString());

    // JSONAssert data with strict=false
    String expectedJSON = "{\"data\":[{\"foo\": \"bar\"}, {\"test\": \"this is test data\"}]}";
    JSONAssert.assertEquals(expectedJSON, response.getBody().asString(), false);

    // How do I extract JSON with JSONPath, use JSONAssert together?
}

Approach 1 - using JSONPath to get JSONObject

How do I get JSONPath to return a JSONObject that can be used by JSONAssert?

In the code example:

Object data = response.then().extract().path("data");

This returns a java.util.ArrayList. How can this be used with JSONAssert to compare to expected JSON?

Approach 2 - parse extracted data with JSONParser

If I do data.toString(), this returns a string that cannot be parsed due to lack of quote handling for string values with spaces strings:

String dataString = response.then().extract().path("data").toString();
JSONArray dataArray = (JSONArray) JSONParser.parseJSON(dataString);

Result:

org.json.JSONException: Unterminated object at character 24 of [{foo=bar}, {test=this is test data}]

Approach 3 - Using JSON schema validation

Is is possible to extract just the data property from the JSON and run that against JSON Schema on just that part?

Note: the entire JSON that is returned is quite large. I just want to validate the data property from it.

What would an example of doing a JSON schema validation look for just the data property from the JSON?

Thanks;

1

There are 1 best solutions below

0
On

You can use the method jsonPath in your response object.

Example:

// this will return bar as per your example response.
String foo = response.jsonPath ().getString ("data[0].foo"); 

For more info about JSon path check here.