I want to validate a JSON string by using com.google.gson.JsonParser
. By this post, I know that JsonParser.parse()
is lenient enough to treat invalid abc as valid "abc". That is to say, JsonParser.parse()
will not throw a JsonSyntaxException
or JsonParseException
for the string below:
abc
By adding the logic of jsonElement.isJsonObject(), the following code can recognize invalid JSON string of abc.
boolean isJSON(String jsonString) {
try {
JsonElement jsonElement = new JsonParser().parse(jsonString);
if (!jsonElement.isJsonObject()) {
return false;
}
} catch (Exception e) {
return false;
}
return true;
}
However, it still cannot recognize invalid JSON format from the following strings.
{"name": mike}
or
{name: mike}
How to recognize invalid JSON for these cases?