Melvin Richard
Melvin Richard

Reputation: 423

RestAssured - Compare two JSON Objects

Using RestAssured I am trying to compare two JSON Objects.

Example : The first JSON is from excel I read it as a String and store it

String a = "Some JSON from Excel and I store it as a String";

The second JSON is a response that returns a Response Object which is actually a JSON

Response expectedResponse = RestAssured.given().contentType("application/json").header(auth).get(endpoint).then().contentType("application/json").extract().response();

I want to compare these two as JSON Objects, because when I convert the response to String and try to compare and if the order of the JSON schema changes, my assertion fails.

I tried for methods to convert the String to JSON but couldn't find any. Could someone help me solving this

Upvotes: 0

Views: 3982

Answers (2)

Ahmed-Amer
Ahmed-Amer

Reputation: 13

You can use objectMapper to achieve what you're looking for, it won't fail if the properties in your object are not in the same order, check this example:

    String s1 = "{ \"employee\": { \"id\": \"1212\", \"fullName\": \"John Miles\", 
    \"age\": 34 } }";
    String s2 = "{ \"employee\": { \"id\": \"1212\", \"age\": 34, \"fullName\": \"John 
    Miles\" } }";
    ObjectMapper mapper = new ObjectMapper();
    JsonNode s1Json = mapper.readTree(s1);
    JsonNode s2Json = mapper.readTree(s2);
    System.out.println(s1Json.equals(s2Json));

Upvotes: 0

Wilfred Clement
Wilfred Clement

Reputation: 2774

If there is an uncertainty in the order of the fields then I would suggest you to use Hamcrest Matchers

You have not posted the responses so I can only give you examples

body(containsString("Hello World"));

or you could also try something like the below

body("find { it.userId == '123' }.subject", containsInAnyOrder("MATHS", "SCIENCE"))

Upvotes: 1

Related Questions