I want to compare two json response. I have tried to store the JSON response in a pojo then compared by overiding equals method but my pojo is very large and consist of 10 classes . Is there any other way to compare
Asked
Active
Viewed 2,878 times
0
-
https://stackoverflow.com/questions/2253750/testing-two-json-objects-for-equality-ignoring-child-order-in-java – Alexey Vlasov Aug 14 '19 at 18:40
-
You can use Jackson to compare 2 JSON , see [this](https://www.baeldung.com/jackson-compare-two-json-objects) – 0cnLaroche Aug 14 '19 at 18:45
2 Answers
0
You may try below code snippet:
import org.codehaus.jettison.json.JSONObject;
import org.junit.Assert;
import io.restassured.RestAssured;
import io.restassured.builder.RequestSpecBuilder;
import io.restassured.filter.cookie.CookieFilter;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
Retrive JSON responses:
Response jsonResponseOne = RestAssured.given().spec(requestSpecification).filter(cookieFilter).relaxedHTTPSValidation().when().///.then().assertThat().extract().response();
Response jsonResponseTwo = RestAssured.given().spec(requestSpecification).filter(cookieFilter).relaxedHTTPSValidation().when().///.then().assertThat().extract().response();
Extract both JSON responses as a string:
JSONObject jsonOne = new JSONObject(jsonResponseOne.getBody().asString())
JSONobject jsonTwo = new JSONObject(jsonResponseTwp.getBody().asString())
Compare response using Java:
Assert.assertEquals(jsonOne, jsonTwo);

Anmol Saxena
- 21
- 1
- 3
0
If you need the differences between them, try to use zjsonpatch library to detect the differences between two json responses.
A sample code:
JsonNode json1= jacksonObjectMapper.readTree(jsonString1);
JsonNode json2= jacksonObjectMapper.readTree(jsonString2);
JsonNode patchNode = JsonDiff.asJson(json1, json2);
String diffs = patchNode.toString();

Gayan Herath
- 1
- 2