0

我正在使用JSONAssert库来比较两个 JSON 数组。

要比较的数组如下所示:

实际的

{"components": [
          {
            "createdAt": "2022-03-03T10:22:01.959148348Z",
            "createdBy": "abc",
            "category": "category-1",
            "uuid": "469ba1b0-5975-49a0-8fa9-4f3ae5436c68"
          },
          {
            "createdAt": "2022-03-03T10:22:01.959152770Z",
            "createdBy": "def",
            "category": "category-2",
            "uuid": "494e0510-c322-4a45-a103-227b5a3a0adc"
          }]
}

预期的

{"components": [
          {
            "createdAt": "2022-03-02T06:58:18.532605787Z",
            "createdBy": "def",
            "category": "category-2",
            "uuid": "78846bb4-5721-447b-ba8b-7fe91bc125a5"
          },
          {
            "createdAt": "2022-03-02T06:58:18.532613344Z",
            "createdBy": "abc",
            "category": "category-1",
            "uuid": "dfe61f6b-addf-442a-8f7c-6e3f249cb4be"
          }]
}

这是代码。

ObjectMapper objectMapper = new ObjectMapper();
        try {
            JSONObject actual = new JSONObject(objectMapper.writeValueAsString(actualEntity.getObj())); // actualEntity and expectedEntity are deserialized with Jackson 
            JSONObject expected = new JSONObject(objectMapper.writeValueAsString(expectedEntity.getObj()));
            ArrayValueMatcher<Object> arrValMatch = new ArrayValueMatcher<>(new CustomComparator(
                    JSONCompareMode.LENIENT,
                    new Customization("components[*].createdAt", (o1, o2) -> true),
                    new Customization("components[*].uuid", (o1, o2) -> true)));
            Customization arrayValueMatchCustomization = new Customization("components", arrValMatch);
            CustomComparator customArrayValueComparator = new CustomComparator(
                    JSONCompareMode.LENIENT,
                    arrayValueMatchCustomization);
            JSONAssert.assertEquals(expected.toString(), actual.toString(), customArrayValueComparator);
        } catch (JsonProcessingException | JSONException e) {
            Assert.fail("Something went wrong while parsing JSON: " + e.getMessage());
        }

这是错误:

java.lang.AssertionError: components[0].category
Expected: category-2
     got: category-1
 ; components[0].createdBy
Expected: def
     got: abc
 ; components[1].category
Expected: category-1
     got: category-2
 ; components[1].createdBy
Expected: abc
     got: def

我不明白为什么当它实际上应该通过LENIENT比较模式时比较失败。

4

1 回答 1

0

我对这里的 Javascript 库不太确定,但有时我遇到过类似的问题,我只是使用JSON 比较器 API如果你想忽略元素或节点的顺序,可以设置忽略顺序。它确实对我有用。我尝试为自己构建 lib,但涉及到许多复杂的算法,我想要更快的分辨率,所以直接使用 API,它可以免费使用。

于 2022-03-03T13:42:33.420 回答