You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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 '}'
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.
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:
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
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)
I'm trying to a validate if a string is a valid json by using object mapper
However this test fails as object mapper recognize below as a valid json. (seems like it ignores the text after first '}'
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
The text was updated successfully, but these errors were encountered: