Back
How do I validate a JSON string in Java? Or could I parse it using regular expressions?
A wild idea, try parsing it and catch the exception:
import org.json.*;public boolean isJSONValid(String test) { try { new JSONObject(test); } catch (JSONException ex) { // edited, to include @Arthur's comment // e.g. in case JSONArray is valid as well... try { new JSONArray(test); } catch (JSONException ex1) { return false; } } return true;}
import org.json.*;
public boolean isJSONValid(String test) {
try {
new JSONObject(test);
} catch (JSONException ex) {
// edited, to include @Arthur's comment
// e.g. in case JSONArray is valid as well...
new JSONArray(test);
} catch (JSONException ex1) {
return false;
}
return true;
This code uses org.json JSON API implementation that is available on github, in maven and partially on Android.
31k questions
32.8k answers
501 comments
693 users