Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Validate json string syntax? #369

Closed
iwidanalage opened this issue Apr 13, 2017 · 2 comments
Closed

Validate json string syntax? #369

iwidanalage opened this issue Apr 13, 2017 · 2 comments

Comments

@iwidanalage
Copy link

I'm trying to a validate if a string is a valid json by using object mapper

  @Test(expected = JsonParseException.class)
  public void isJsonObject_withInvalidJson() throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.readTree("{\"Name\":\"hello\"}\" *;s; little blob of dataaa");
    Assert.fail("Above line should throw");
  }

However this test fails as object mapper recognize below as a valid json. (seems like it ignores the text after first '}'

{"Name":"hello"}" *;s; little blob of dataaa{}

Is there a flag or something that i missed to set on ObjectMapper to do strict validation? Similar to
https://google.github.io/gson/apidocs/com/google/gson/GsonBuilder.html#setLenient

@cowtowncoder
Copy link
Member

No, it's not a bug but feature. Only part of stream that is valid single JSON Value -- in this case JSON Object -- is read, rest is not consumed. If JsonParser is read from after readValue() (when passing parser, not input source), an exception would be thrown.

There is a feature request:

FasterXML/jackson-databind#1583

that would allow forcing reading of all content, which would trigger the exception. It has not yet been implemented but is planned to be added for 2.9.

But before that it is possible to do validation, with couple of alternative ways:

  1. Construct JsonParser directly, pass that to readValue(), and after call, verify that parser.nextToken() returns null -- if there is invalid content, that will trigger exception; or if valid root-level values (sequences of white-space separated tokens are allowed by parser), may consider failure too
  2. Construct MappingIterator (need to construct ObjectReader from mapper, then call readValues()), iterate to get first value, then iterate once more to get null (and either get an exception, null, or another value -- of which only null is what you want)

@iwidanalage
Copy link
Author

@cowtowncoder thanks. I'll give it a try.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants