I would like to validate one string fetched as a response from a server. The response must be a valid JSON string. Sometimes, when the user is over a network that requires authentication or a PHP error happens, the response isn’t a valid JSON.
Android parser JSONTokener don’t validates strings before parsing them, so under that cases the application throws a JSONException and force closes.
I catched the exception, but application is still closing.
My question is: Is there any JSON validator for objects and strings to validate them first and avoid parsing them if they have an invalid format?
Another solution is checking if string[0] has “{” or “[” but this solution isn’t elegant and will miss a lot of errors. So I would like to use a full JSON validator.
Thanks in advance.
Are you using GSON?
If so the library raises a JsonSyntaxException when parsing a malformed JSON string
If you are using android.util.JsonReader a MalformedJsonException is thrown by the JsonReader