Getting a diff of two JSON strings using Java code

后端 未结 4 1017
无人及你
无人及你 2020-12-15 21:55

Can anybody suggest some Java Library or Code to get a diff of two JSON Strings?

4条回答
  •  忘掉有多难
    2020-12-15 22:30

    For one specific suggestion, you could use Jackson, bind JSON strings into JSON trees, and compare them for equality. Something like:

    ObjectMapper mapper = new ObjectMapper();
    JsonNode tree1 = mapper.readTree(jsonString1);
    JsonNode tree2 = mapper.readTree(jsonString2);
    if (tree1.equals(tree2)) { 
      // yes, contents are equal -- note, ordering of arrays matters, objects not
    } else { 
      // not equal
    }
    

    equality comparison is by value and should work as expected with respect to JSON arrays, objects and primitive values.

提交回复
热议问题