Test if it is JSONObject or JSONArray

Something like this should do it:

JSONObject json;
Object     intervention;
JSONArray  interventionJsonArray;
JSONObject interventionObject;

json = RestManager.getJSONfromURL(myuri); // retrieve the entire json stream     
Object intervention = json.get("intervention");
if (intervention instanceof JSONArray) {
    // It's an array
    interventionJsonArray = (JSONArray)intervention;
else if (intervention instanceof JSONObject) {
    // It's an object
    interventionObject = (JSONObject)intervention;
else {
    // It's something else, like a string or number

This has the advantage of getting the property value from the main JSONObject just once. Since getting the property value involves walking a hash tree or similar, that’s useful for performance (for what it’s worth).

Leave a Comment