JSONAssert 需要比较两个 JSON 字符串:
字符串A
{
"items": [
"SfWn8eQ",
"QiOiJrw",
"2Npc2Nv"
],
"auths": [
"5895c0a1-0fa9-4222-bbfb-5f96f6737cd7",
"415499a6-daa3-45b7-b967-83aa94a38da1",
"5d572399-a2ae-4bc4-b989-e2115028612e"
]
}
字符串B
{
"items": [
"SfWn8eQ",
"QiOiJrw",
"2Npc2Nv"
],
"auths": [
"415499a6-daa3-45b7-b967-83aa94a38da1",
"5d572399-a2ae-4bc4-b989-e2115028612e",
"5895c0a1-0fa9-4222-bbfb-5f96f6737cd7"
]
}
两个 JSON 字符串应该相等:
items
在模式下比较STRICT
,即“严格检查。不可扩展,严格的数组排序”。auths
在模式下比较NON_EXTENSIBLE
,即“不可扩展检查。不可扩展,非严格数组排序”。
换句话说,比较对于 是顺序敏感的,items
但对于 是顺序容错的auths
。
JSONAssert
代码是:
CustomComparator comparator = new CustomComparator(JSONCompareMode.NON_EXTENSIBLE,
new Customization("auths",
// A lenient comparison for auths. Compare ignoring the order.
(o1, o2) -> (
TestUtil.equals(((List<String>)o1), ((List<String>)o2))
)
)
);
try {
JSONAssert.assertEquals(expected, actual, comparator);
} catch (JSONException e) {
Assert.fail();
}
忽略顺序比较两个字符串列表的TestUtil
代码是:
public class KmsAgentTestUtil {
public static boolean equals(List<String> auths1, List<String> auths2) {
if (CollectionUtils.isEmpty(auths1) && CollectionUtils.isEmpty(auths2)) {
return true;
}
Collections.sort(auths1);
Collections.sort(auths2);
return auths1.equals(auths2);
}
}
它会出错,因为它不符合JSONAssert
约定,但我还没有找到另一种解决方案。有人帮帮我吗?