I need some help coming with a reliable JSON string validator - a method which intake a string and checks if it's a valid JSON. Example: if I pass {"color":"red"}
or {"amount":15}
it will pass but something like "My invalid json"
will not. In short I need something that is as reliable as www.jsonlint.com validator. BTW - I'm not interested in deserializing into java object, because that's not my requirement. I may receive an arbitrary string and all I have to do is validate it has a valid JSON format.
I have already researched on this forum several posts on the subject regarding java JSON string validations.
What I have done so far:
I tried using these classes: org.json.JSONObject
and org.json.JSONArray
in the following manner:
private static boolean isValidJSONStringObject(String requestBody){
try {
new JSONObject(requestBody);
} catch (JSONException jsonEx) {
return false;
}
return true;
}
private static boolean isValidJSONStringArray(String requestBody) {
try {
new JSONArray(requestBody);
} catch (JSONException jsonEx) {
return false;
}
return true;
}
However, the following strings (entire lines) still go through, and they shouldn't:
{"color":"red"}{"var":"value"}
[1,2,3][true,false]
in other words when I have objects/arrays repeated w/out any encapsulation in some parent object. If you paste these lines in www.jsonlint.com validator they both fail.
I know there is always a regex option but I gess that cannot be guaranteed 100% because of the recursive nature of JSON and those regex expressions are going to be rather complex.
Any help will be greatly appreciated!