首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在JSONAssert java中使用REGEX验证JSON字符串

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

Stack Overflow用户
提问于 2018-11-13 04:15:17
回答 1查看 1.8K关注 0票数 1

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

代码语言:javascript
复制
{
  "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 )。

代码语言:javascript
复制
    JSONAssert.assertEquals(getJsonBody(expected), response.asString(),false);

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

代码语言:javascript
复制
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

对这个错误有什么建议吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-11-13 04:40:50

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

试试这个代码:-

代码语言:javascript
复制
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<>())
        )
);

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

代码语言:javascript
复制
JSONAssert.assertEquals(
        getJsonBody(expected),
        response.asString(),
        new CustomComparator(
                JSONCompareMode.LENIENT,
                new Customization("***", new RegularExpressionValueMatcher<>())
        )
);
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53273716

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档