How to check whether a given string is valid JSON in Java

sappu picture sappu · Apr 16, 2012 · Viewed 249.3k times · Source

How do I validate a JSON string in Java? Or could I parse it using regular expressions?

Answer

MByD picture MByD · Apr 16, 2012

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;
}

This code uses org.json JSON API implementation that is available on github, in maven and partially on Android.