java - 当响应顺序不同时如何比较两个JSon响应
问题描述
以下是我收到的两个 API 调用的响应,响应相同,但数据顺序不正确:
{"URI":"CoGroup/2","level":"total","name":null,"code":null,"baseColor":null,"secondaryColor":null,"selected":null,"value":317978,"Byyear":[],"count":10499},
{"URI":"integer/7005","level":"total","name":null,"code":null,"baseColor":null,"secondaryColor":null,"selected":null,"value":26857,"Byyear":[],"count":4542},
{"URI":"intgroup/78","level":"total","name":null,"code":null,"baseColor":null,"secondaryColor":null,"selected":null,"value":105304,"Byyear":[],"count":1653}
]
[
{"URI":"CoGroup/2","level":"total","name":null,"code":null,"baseColor":null,"secondaryColor":null,"selected":null,"value":317978,"Byyear":[],"count":10499},
{"URI":"intgroup/78","level":"total","name":null,"code":null,"baseColor":null,"secondaryColor":null,"selected":null,"value":105304,"Byyear":[],"count":1653},
{"URI":"integer/7005","level":"total","name":null,"code":null,"baseColor":null,"secondaryColor":null,"selected":null,"value":26857,"Byyear":[],"count":4542}
]
我尝试使用 Jackson 来比较使用 mapper.readtree 的响应,但结果返回为 false。
ObjectMapper mapper1 = new ObjectMapper();
ObjectMapper mapper2 = new ObjectMapper();
try{
assertEquals(mapper1.readTree(respStr1), mapper2.readTree(respStr2));
}
catch(Exception e) {
System.out.println(e);
}
and
ObjectMapper mapper1 = new ObjectMapper();
JsonNode tree1 = mapper1.readTree(respStr1);
JsonNode tree2 = mapper1.readTree(respStr2);
System.out.println(tree1.equals(tree2));
关于如何在此处进行比较的任何建议....
解决方案
为此,您可以使用scyscreamer的 JSONAssert 库。
它会像这样工作:
// respStr1 and respStr2 are the two json in string
JSONAssert.assertEquals(respStr1, respStr2, JSONCompareMode.NON_EXTENSIBLE);
NON_EXTENSIBLE
如果 json 仅在顺序上有所不同,则模式将允许断言通过。
编辑:
JSONCompare.compareJSON(respStr1, respStr2, CompareMode.NON_EXTENSIBLE).passed()
如果比较通过,将返回。
推荐阅读
- java - 如何使用 Java Spring Boot 更新 MognoDB 中的数组字段?
- select - 添加到购物车 - 从带有添加到购物车按钮的下拉变体选择更改为 Shopify / Liquid 上每个变体的单个添加到购物车按钮
- linker - 在调试信息压缩标志的各种组合下,汇编器和链接器之间的压缩调试信息如何流动?
- python - 使用 Paramiko (Python) 通过 SSH 执行 smartctl 命令时没有输出
- android - Android Firebase:如何创建适用于我现有通知系统的通知通道
- json - MySQL JSON 数组 - 按最后一个键排序
- c++ - 对实现文件中定义的构造函数的未定义引用
- javascript - 如何将现有库添加为依赖于我的新库?反应原生
- c++ - C++ 无法迭代函数返回的对象数组,段错误
- spring-boot - 在resilience4j中重试+断路器