Test if it is JSONObject or JSONArray

JavaJson

Java Problem Overview


I have a json stream which can be something like :

{"intervention":
	 
	{ 
	  "id":"3",
              "subject":"dddd",
              "details":"dddd",
              "beginDate":"2012-03-08T00:00:00+01:00",
              "endDate":"2012-03-18T00:00:00+01:00",
              "campus":
                       { 
                         "id":"2",
                         "name":"paris"
                       }
    }
}

or something like

{"intervention":
            [{
              "id":"1",
              "subject":"android",
              "details":"test",
              "beginDate":"2012-03-26T00:00:00+02:00",
              "endDate":"2012-04-09T00:00:00+02:00",
              "campus":{
                        "id":"1",
                        "name":"lille"
                       }
            },

	{
	 "id":"2",
             "subject":"lozlzozlo",
             "details":"xxx",
             "beginDate":"2012-03-14T00:00:00+01:00",
             "endDate":"2012-03-18T00:00:00+01:00",
             "campus":{
                       "id":"1",
                       "name":"lille"
                      }
            }]
}	

In my Java code I do the following:

JSONObject json = RestManager.getJSONfromURL(myuri); // retrieve the entire json stream  	
JSONArray  interventionJsonArray = json.getJSONArray("intervention");

In the first case, the above doesn't work because there is only one element in the stream.. How do I check if the stream is an object or an array ?

I tried with json.length() but it didn't work..

Thanks

Java Solutions


Solution 1 - Java

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).

Solution 2 - Java

Maybe a check like this?

JSONObject intervention = json.optJSONObject("intervention");

This returns a JSONObject or null if the intervention object is not a JSON object. Next, do this:

JSONArray interventions;
if(intervention == null)
        interventions=jsonObject.optJSONArray("intervention");

This will return you an array if it's a valid JSONArray or else it will give null.

Solution 3 - Java

To make it simple, you can just check first string from server result.

String result = EntityUtils.toString(httpResponse.getEntity()); //this function produce JSON
String firstChar = String.valueOf(result.charAt(0));

if (firstChar.equalsIgnoreCase("[")) {
    //json array
}else{
    //json object
}

This trick is just based on String of JSON format {foo : "bar"} (object) or [ {foo : "bar"}, {foo: "bar2"} ] (array)

Solution 4 - Java

You can get the Object of the input string by using below code.

String data = "{ ... }";
Object json = new JSONTokener(data).nextValue();
if (json instanceof JSONObject)
 //do something for JSONObject
else if (json instanceof JSONArray)
 //do something for JSONArray

Link: https://developer.android.com/reference/org/json/JSONTokener#nextValue

Solution 5 - Java

      Object valueObj = uiJSON.get(keyValue);
		if (valueObj instanceof JSONObject) {
			this.parseJSON((JSONObject) valueObj);
		} else if (valueObj instanceof JSONArray) {
			this.parseJSONArray((JSONArray) valueObj);
		} else if(keyValue.equalsIgnoreCase("type")) {
			this.addFlagKey((String) valueObj);
		}

// ITERATE JSONARRAY private void parseJSONArray(JSONArray jsonArray) throws JSONException { for (Iterator iterator = jsonArray.iterator(); iterator.hasNext();) { JSONObject object = (JSONObject) iterator.next(); this.parseJSON(object); } }

Solution 6 - Java

I haven't tryied it, but maybe...


JsonObject jRoot = RestManager.getJSONfromURL(myuri); // retrieve the entire json stream
JsonElement interventionElement = jRoot.get("intervention");
JsonArray interventionList = new JsonArray();




if(interventionElement.isJsonArray()) interventionList.addAll(interventionElement.getAsJsonArray());
else interventionList.add(interventionElement);

if(interventionElement.isJsonArray()) interventionList.addAll(interventionElement.getAsJsonArray()); else interventionList.add(interventionElement);

If it's a JsonArray object, just use getAsJsonArray() to cast it. If not, it's a single element so just add it.

Anyway, your first exemple is broken, you should ask server's owner to fix it. A JSON data structure must be consistent. It's not just because sometime intervention comes with only 1 element that it doesn't need to be an array. If it has only 1 element, it will be an array of only 1 element, but still must be an array, so that clients can parse it using always the same schema.

Solution 7 - Java

    //returns boolean as true if it is JSONObject else returns boolean false 
public static boolean returnBooleanBasedOnJsonObject(Object jsonVal){
		boolean h = false;
		try {
			JSONObject j1=(JSONObject)jsonVal;
			h=true;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
   if(e.toString().contains("org.json.simple.JSONArray cannot be cast to     org.json.simple.JSONObject")){
				h=false;
			}
		}
		return h;
		
	}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTangView Question on Stackoverflow
Solution 1 - JavaT.J. CrowderView Answer on Stackoverflow
Solution 2 - JavaNathan QView Answer on Stackoverflow
Solution 3 - Javaazwar_akbarView Answer on Stackoverflow
Solution 4 - JavaVirendra KachhiView Answer on Stackoverflow
Solution 5 - JavaSagar JadhavView Answer on Stackoverflow
Solution 6 - Javauser1930830View Answer on Stackoverflow
Solution 7 - JavaharoonView Answer on Stackoverflow