json差异比较
如何比较两个json的差异
代码实现
- 导入依赖
<dependency><groupId>cn.xiaoandcai</groupId><artifactId>json-diff</artifactId><!-- 旧版本可能存在某些缺陷。版本请以maven仓库最版为准。 --><version>4.1.3-RC1-RELEASE</version></dependency><!-- 选择json解析框架。fastjson, fastjson2,gson,jackson 之一 --><dependency><groupId>cn.xiaoandcai</groupId><artifactId>json-diff-impl-fastjson</artifactId><version>4.1.3-RC1-RELEASE</version></dependency>
- 用例实现
@Testpublic void testJsonDiff() throws JSONException, JsonProcessingException {String json1 = "{\"name\":\"John\", \"age\":30, \"city\":\"New York\",\"phone\":\"13800000000\",\"dog\":{\"age\":4,\"name\":\"mojo\",\"weight\":\"21.5\"}}";String json2 = "{\"name\":\"John\", \"age\":35, \"city\":\"Chicago\",\"qq\":\"123456789\",\"dog\":{\"name\":\"mojo\",\"age\":\"2\",\"color\":\"red\"}}";JsonComparedOption jsonComparedOption = new JsonComparedOption().setIgnoreOrder(true);JsonCompareResult jsonCompareResult = new DefaultJsonDifference().option(jsonComparedOption).detectDiff(json1, json2);List<Defects> defectsList = jsonCompareResult.getDefectsList();for (Defects d : defectsList) {Object actual = d.getActual();Object expect = d.getExpect();System.out.println("路径:" + d.getTravelPath().getAbstractTravelPath() + ",旧值:" + expect + ",新值:" + actual);}}
执行结果