Search code examples
javajsonjsonassert

Validate JSON String using REGEX in JSONAssert java


I am storing my expected json string in the json file under resources as shown below. The json string consists of regular expression. I am using JSONAssert Library to compare two json strings.

{
  "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"
}

My actual response consists of timestamp in this format 2018-11-13T04:10:11.233+0000

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

Is always giving the below error on the regular expression

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

Any recommendation on this error?


Solution

  • You are comparing the pattern with the timestamp string. What you actually need to do is check if the timestamp matches the pattern.

    Try this code:-

    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<>())
            )
    );
    

    So with your code, it will look something like:-

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