My Question: How can I improve these methods to check that a string is valid json without having to ignore JSONExceptions by using the official JSON for java library?
public boolean isValidJSON(String possibleJson) {
return isJSONObject(possibleJson) || isJSONArray(possibleJson);
}
private boolean isJSONObject(String possibleJson) {
try {
new JSONObject(possibleJson);
return true;
} catch (JSONException ex) {
return false;
}
}
private boolean isJSONArray(String possibleJson) {
try {
new JSONArray(possibleJson);
return true;
} catch (JSONException ex) {
return false;
}
}
I'm pretty sure it's not best practices to depend on exceptions thrown as part of logic in a method. Is there another way to do this?
Note: Remember, I would prefer to not use other libraries to do this. It is a small part of a big project and I don't want to introduce another dependency if I can help it.