0

I would like to compare two rest api responses in Java. Currently I am using zjsonpatch library and with that I am able to get the difference but the difference contains the value of one of the jsons. I would like to have both the json nodes.

Please find below my code:

    ObjectMapper jacksonObjectMapper = new ObjectMapper();
    JsonNode beforeNode = jacksonObjectMapper.readTree(jsonActual);
    JsonNode afterNode = jacksonObjectMapper.readTree(jsonCurrent);
    JsonPatch patch = JsonDiff.asJsonPatch(beforeNode, afterNode);
    String diffs = patch.toString();

Below is the output I am getting

op: replace; path: "/businessServiceabilityResponse/0/serviceabilityDetail/0/serviceabilitySource"; value: "ELOC"]

Is there a way I can get both the nodes which are not matching?

mentallurg
  • 4,967
  • 5
  • 28
  • 36
Sourabh Roy
  • 159
  • 1
  • 18
  • Does this answer your question? [How to compare two JsonNodes with Jackson?](https://stackoverflow.com/questions/53871675/how-to-compare-two-jsonnodes-with-jackson) – Jasper Huzen Jan 23 '20 at 21:49
  • No. This is doing only assertion and returning a boolean. – Sourabh Roy Jan 23 '20 at 21:57
  • What exactly do you want in the output? Node at `/businessServiceabilityResponse/0/serviceabilityDetail/0`? – Smile Jan 24 '20 at 08:57
  • @Smile I want the nodes of both the files which are different like /businessServiceabilityResponse/0/serviceabilityDetail/0/serviceabilitySource"; value: "ELOC"] and /businessServiceabilityResponse/0/serviceabilityDetail/0/serviceabilitySource"; value: "ELOC1"]... This will clearly show the difference – Sourabh Roy Jan 24 '20 at 14:52
  • I don't know if any libarary can do this out of box. But you can write some custom logic to find the mismatching values from both json file based on the path returned by zjsonpatch – Smile Jan 25 '20 at 09:43
  • @Smile could you please elaborate more on what you are suggesting. Thanks – Sourabh Roy Jan 29 '20 at 04:09

1 Answers1

0

You can try using JSONAssert

JSONAssert.assertEquals(json1, json2, true);

json1:

[
  {
    studentname: "John",
    john: "123"
  },
  {
    studentname: "Ram",
    Ram: "124"
  }
]

json2

[
  {
    studentname: "Nhoj",
    john: "123"
  },
  {
    studentname: "Ram",
    Ram: "124"
  }
]

Output:

Exception in thread "main" java.lang.AssertionError: [0].studentname
Expected: john
     got: Nhoj

    at org.skyscreamer.jsonassert.JSONAssert.assertEquals(JSONAssert.java:417)
    at org.skyscreamer.jsonassert.JSONAssert.assertEquals(JSONAssert.java:394)
    at org.skyscreamer.jsonassert.JSONAssert.assertEquals(JSONAssert.java:336)
    at com.smilep.java.thirteen.so.JSONAssertExample.main(JSONAssertExample.java:32)
Smile
  • 3,832
  • 3
  • 25
  • 39