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!
Validating with JSONObject String json = "{\"email\": \"example@com\", \"name\": \"John\"}"; assertTrue(validator. isValid(json)); String json = "Invalid_Json"; assertFalse(validator. isValid(json));
The best way to find and correct errors while simultaneously saving time is to use an online tool such as JSONLint. JSONLint will check the validity of your JSON code, detect and point out line numbers of the code containing errors.
Designed for Java, it can also handle other non-JSON encodings. It's the most popular JSON parser, according to our findings on Github usages. Oracle's JSONP: https://jsonp.java.netJSONP (JSON Processing) is a Java API for JSON processing, namely around consuming and producing streaming JSON text.
Gson can handle this. Here is an example:
public boolean isValid(String json) {
try {
new JsonParser().parse(json);
return true;
} catch (JsonSyntaxException jse) {
return false;
}
}
String json = "{\"color\":\"red\"}{\"var\":\"value\"}";
System.out.println(isValid(json));
Note that Gson does allow some leniency in input JSON, which might not be desired. For example, unquoted keys are automatically converted to quoted ones by the parser. This may or may not be a deal-breaker depending on your expected usage.
Here is our solution for now. Using the two different libraries (gson - first private method and jackson - second private method) is not ideal but at least we are passing all of our unit/integration tests. I bet we can do all we need with just the jackson tools.
public static boolean isStringValidJSON(String jsonString) {
return (isJSONStringObjectOrArray(jsonString) && isJSONStringParsable(jsonString));
}
private static boolean isJSONStringObjectOrArray(String jsonString) {
try {
JsonElement element = new JsonParser().parse(jsonString);
return (element.isJsonObject() || element.isJsonArray());
} catch (JsonSyntaxException jsonEx) {
return false;
}
}
private static boolean isJSONStringParsable(String jsonString) {
try {
org.codehaus.jackson.JsonParser parser =
new ObjectMapper().getJsonFactory().createJsonParser(jsonString);
while(parser.nextToken() != null) {
}
return true;
} catch (JsonParseException e) {
return false;
} catch (IOException e) {
return false;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With