在比较Java

时间:2018-06-19 02:19:22

标签: java json jsonassert

我想比较Java 8中的两个JSON字符串是否相等,但是忽略特定的已知节点,这些节点包含预期不同的值并且是容忍的差异,例如:时间戳。 目前正在使用org.SkyScreamer的JSONAssert v1.5.0,我能够“忽略”其中的一些节点,但不能“忽略”数组中的节点。

我想要的是扩展我当前的JSONComparator以包含一个Customization,它的第一个'path'参数有一个数组地址。

JSONComparator customisedJobComparator = new CustomComparator(JSONCompareMode.NON_EXTENSIBLE,
            new Customization("id", (o1, o2) -> true),
            new Customization("appointmentBookedDate.$date", (o1, o2) -> true),
            ...
            new Customization("someArray[n].timestamp", (o1, o2) -> true) //<--- this is wrong, what is the correct way for this path address?
            );

以下代码是我尝试提供解决方案;除了anArray []。id值之外,预期/实际JSON字符串都是相同的。 我希望此测试通过,但失败并出现错误: java.lang.AssertionError:anArray [0]找不到元素{“id”的匹配:“valueA”}

@Test
public void compareJsonStrIgnoringDiffInArray() {
    String errorMsg = "";
    String expectedJsonStr = "{\"anArray\": [{\"id\": \"valueA\"}, {\"colour\": \"Blue\"}]}";
    String actualJsonStr = "{\"anArray\": [{\"id\": \"valueB\"}, {\"colour\": \"Blue\"}]}";

    //Create custom comparator which compares two json strings but ignores reporting any differences for anArray[n].id values
    //as they are a tolerated difference
    Customization customization = new Customization("anArray[n].id", (o1, o2) -> true);
    JSONComparator customisedComparator = new CustomComparator(JSONCompareMode.NON_EXTENSIBLE, customization);

    JSONAssert.assertEquals(errorMsg, expectedJsonStr, actualJsonStr, customisedComparator);
}

2 个答案:

答案 0 :(得分:3)

javadoc for JSONAssert中进行了一些挖掘之后,我看到了一个使用了一系列对象的示例。从那个例子我可以修改你的测试用例:

let headlineFont = UIFont.preferredFont(forTextStyle: UIFontTextStyle.headline)
let subheadFont = UIFont.preferredFont(forTextStyle: UIFontTextStyle.subheadline)

答案 1 :(得分:0)

根据我的要求,需要忽略字段 businessCorrelationId 只出现一次,effectiveStartDate 出现在 data 的每个节点中。

{
  "messageElements": {
    "messageStatus": "SUCCESS",
    "businessCorrelationId": "a80337639eb40758",
    "errorList": []
  },
  "data": [
    {
      "referenceId": 1,
      "category": "CAT1",
      "subCategory": "SUB1",
      "effectiveStartDate": "2021-02-08T00:00:00",
      "activeFlg": true,
      "version": 1
    },
    {
      "referenceId": 2,
      "category": "CAT2",
      "subCategory": "SUB2",
      "effectiveStartDate": "2021-02-08T00:00:00",
      "effectiveEndDate": null,
      "activeFlg": true,
      "version": 1
    },
    {
      "referenceId": 3,
      "category": "CAT3",
      "subCategory": "SUB3",
      "effectiveStartDate": "2021-02-08T00:00:00",
      "activeFlg": true,
      "version": 1
    }
  ],
  "tenant": {
    "tenantId": null,
    "timeZoneOffset": null,
    "name": null
  }
}

以下代码运行良好。

JSONAssert.assertEquals(expectedJson, actualJson, new CustomComparator(JSONCompareMode.LENIENT,
   new Customization("data[*].createdTimestamp", (ct1, ct2) -> true),
   new Customization("messageElements.businessCorrelationId", (c1, c2) -> true)));