您好,登錄后才能下訂單哦!
本篇內容介紹了“用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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。