本篇内容介绍了“用JSONassert对JSON对象进行比较”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!
在日常工作中,会接到用户提出一张订单,修改后需要记录每次修改的信息,然后需要查看修改前后的差异信息这样的需求。要实现这样的功能方式有很多。下面介绍下JSONassert
的简单使用,也方便自己后续使用查看。
JSONassert GitHub地址:https://github.com/skyscreamer/JSONassert
Maven依赖:
<dependency> <groupId>org.skyscreamer</groupId> <artifactId>jsonassert</artifactId> <version>1.5.0</version> <scope>test</scope> </dependency>
初始化数据:
private Grade getBeforeGrade(){ Grade grade = new Grade(); grade.setCode("A01"); grade.setName("三年级1班"); List<Student> students = Lists.newArrayList(); students.add(new Student().setCode("001").setName("小A")); students.add(new Student().setCode("002").setName("小B")); grade.setStudents(students); return grade; } private Grade getAfterGrade(){ Grade grade = new Grade(); grade.setCode("A02"); grade.setName("三年级2班"); List<Student> students = Lists.newArrayList(); students.add(new Student().setCode("001").setName("小A")); students.add(new Student().setCode("003").setName("小C")); grade.setStudents(students); return grade; }
CustomComparator customComparator = new CustomComparator(JSONCompareMode.NON_EXTENSIBLE); try { JSONCompareResult result = JSONCompare.compareJSON(JSON.toJSONString(before), JSON.toJSONString(after), customComparator); result.getFieldFailures().forEach(fieldComparisonFailure -> { System.out.println(String.format("变更字段:%s,变更前值:%s,变更后值:%s",fieldComparisonFailure.getField(),fieldComparisonFailure.getExpected(),fieldComparisonFailure.getActual())); }); }catch (Exception e){ e.printStackTrace(); } 输出结果: 变更字段:name,变更前值:小A,变更后值:小B
CustomComparator customComparator = new CustomComparator(JSONCompareMode.NON_EXTENSIBLE, new Customization("name",(o1,o2)->true)); -------------------------------------------------------------- 输出结果: 变更字段:code,变更前值:A01,变更后值:A02
如果JSON对象里面有集合,对比时也需要排除:
ArrayValueMatcher<Object> arrayValueMatcher = new ArrayValueMatcher(new CustomComparator(JSONCompareMode.NON_EXTENSIBLE, new Customization("students[*].code",(o1,o2)->true))); CustomComparator customComparator = new CustomComparator(JSONCompareMode.NON_EXTENSIBLE, new Customization("name",(o1,o2)->true), new Customization("students",arrayValueMatcher)); ------------------------------------------------------------ 输出结果: 变更字段:code,变更前值:A01,变更后值:A02 变更字段:students[1].name,变更前值:小B,变更后值:小C
“用JSONassert对JSON对象进行比较”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注亿速云网站,小编将为大家输出更多高质量的实用文章!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。