在JSONAssert Java中使用REGEX验证JSON字符串

时间:2018-11-13 04:15:17

标签: java json jsonassert

我将预期的json字符串存储在json文件中的资源下,如下所示。 json字符串由正则表达式组成。我正在使用JSONAssert库比较两个json字符串。

{
  "timestamp": "^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}.\\d{3}+\\d{4}$",
  "status": 415,
  "error": "Unsupported Media Type",
  "message": "Content type 'text/plain;charset=ISO-8859-1' not supported",
  "path": "/service/addUser"
}

我的实际回复包含时间戳,格式为2018-11-13T04:10:11.233+0000

    JSONAssert.assertEquals(getJsonBody(expected), response.asString(),false);

总是在正则表达式中给出以下错误

java.lang.AssertionError: timestamp
 Expected: ^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.\d{3}+\d{4}$
      got: 2018-11-13T04:12:55.923+0000

对此错误有何建议?

1 个答案:

答案 0 :(得分:2)

您正在将模式与时间戳字符串进行比较。您实际需要做的是检查时间戳是否匹配模式。

尝试此代码:-

String expected = "{\n" +
        "  \"timestamp\": \"^\\\\d{4}-\\\\d{2}-\\\\d{2}T\\\\d{2}:\\\\d{2}:\\\\d{2}\\\\.\\\\d{3}\\\\+\\\\d{4}$\",\n" +
        "  \"status\": 415,\n" +
        "  \"error\": \"Unsupported Media Type\",\n" +
        "  \"message\": \"Content type 'text/plain;charset=ISO-8859-1' not supported\",\n" +
        "  \"path\": \"/service/addUser\"\n" +
        "}";
String actual = "{\n" +
        "  \"timestamp\": \"2018-11-13T04:12:55.923+0000\",\n" +
        "  \"status\": 415,\n" +
        "  \"error\": \"Unsupported Media Type\",\n" +
        "  \"message\": \"Content type 'text/plain;charset=ISO-8859-1' not supported\",\n" +
        "  \"path\": \"/service/addUser\"\n" +
        "}";
JSONAssert.assertEquals(
        expected,
        actual,
        new CustomComparator(
                JSONCompareMode.LENIENT,
                new Customization("***", new RegularExpressionValueMatcher<>())
        )
);

因此,您的代码将类似于:-

JSONAssert.assertEquals(
        getJsonBody(expected),
        response.asString(),
        new CustomComparator(
                JSONCompareMode.LENIENT,
                new Customization("***", new RegularExpressionValueMatcher<>())
        )
);