0

I need to check if a given input string is a valid json. Unfortunately, all the suggestions I found around the internet, that is to deserialize the given string by using Jackson, Gson, javax.json do not fail on extra characters at the end.

I need such check for a valid json to fail on following inputs

{"a": "b"}
foobar{}

or

{"a":"b"}
{"1":"2"}

or

{"a":"b"},
{"1":"2"}

all the deserializers unfortunately stop after the first closing bracket b"} and basically validate that {"a":"b"} is a valid JSON while omitting the extra characters.

Any idea how to identify the extra characters at the end of the JSON string, or how to enable strict parsing with common Java JSON libraries? Or maybe use completely different tool so that check passes on valid JSONs and fails on cases I'm listing above?


SOLUTION

As a matter of fact, Google GSON with setLenient(false) (the default) happens to validate the input string exactly as I need. So doing

new Gson().fromJson(inputString, Object.class)

is the way to go.

Stepan Vavra
  • 3,884
  • 5
  • 29
  • 40
  • How about comparing the validated string and the original one? If there are extra characters the strings will not be equal. – TDG Mar 30 '22 at 09:38
  • Does this solve your issue? https://stackoverflow.com/questions/2583472/regex-to-validate-json – Morph21 Mar 30 '22 at 09:41
  • @Szprota21 the regex way would probably work but it feels wrong considering the fact that I have available Google's Gson or Jackson or any other library :) but thx! – Stepan Vavra Mar 30 '22 at 09:50
  • @Szprota21 I was looking at the post you linked and it honestly seems like I theoretical debate. People were adding more and more counter examples and as a result the original regex was evolving and yet it's not proven to be working. There's no community around it, no library, no publicly accessible tests or verification of such. Additionally, different regex implementations (java, php, perl, etc) can support such complex regex differently. At least such regex would need to be written exactly for the specific implementation. – Stepan Vavra Mar 30 '22 at 10:05
  • @StepanVavra that's good point. Btw why exactly do you need to validate plain string instead of just parsing it to desired object? Did you want to do some global check for input validity? What's the use case here? – Morph21 Mar 30 '22 at 10:10

0 Answers0