【发布时间】:2020-08-09 11:09:00
【问题描述】:
有两个 JSON 字符串要被 JSONAssert 比较:
字符串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 字符串应该相等:
- 在
STRICT模式下比较items,即“严格检查。不可扩展,严格的数组排序。” - 在
NON_EXTENSIBLE模式下比较auths,即“不可扩展检查。不可扩展,非严格的数组排序。”
换句话说,比较对于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 约定而出错,但我还没有找到其他解决方案。有人帮帮我吗?
【问题讨论】:
-
“它得到错误”你得到什么错误?
标签: java jsonassert