当响应顺序不同时,如何比较两个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比较响应,但结果是错误的。

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));

关于如何在这里进行比较的任何建议。。。。

您可以使用库JSONAssert by scyscreamer来实现此目的。

它会这样工作:

// respStr1 and respStr2 are the two json in string
JSONAssert.assertEquals(respStr1, respStr2, JSONCompareMode.NON_EXTENSIBLE);

如果json的顺序不同,NON_EXTENSIBLE模式将允许断言通过。

编辑:如果比较通过,JSONCompare.compareJSON(respStr1, respStr2, CompareMode.NON_EXTENSIBLE).passed()将返回。

相关内容

  • 没有找到相关文章

最新更新