使用JSONassert进行JSON对象对比
在日常工作中,会接到用户提出一张订单,修改后需要记录每次修改的信息,然后需要查看修改前后的差异信息这样的需求。要实现这样的功能方式有很多。下面介绍下JSONassert
的简单使用,也方便自己后续使用查看。
JSONassert GitHub地址:https://github.com/skyscreamer/JSONassert
1、准备
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;
}
2、简单使用
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
3、扩展功能
3.1、排除不需要对比的字段
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