23

How to check whether an element is a JSONArray or JSONObject. I wrote the code to check,

if(jsonObject.getJSONObject("Category").getClass().isArray()) {

} else {

}

In this case if the element 'category' is JSONObject then it work fine but if it contains an array then it throw exception: JSONArray cannot be converted to JSONObject. Please help. Thanks.

Neetesh
  • 917
  • 1
  • 6
  • 16

5 Answers5

26

Yes, this is because the getJSONObject("category") will try to convert that String to a JSONObject what which will throw a JSONException. You should do the following:

Check if that object is a JSONObject by using:

   JSONObject category=jsonObject.optJSONObject("Category");

which will return a JSONObject or null if the category object is not a json object. Then you do the following:

   JSONArray categories;
   if(category == null)
        categories=jsonObject.optJSONArray("Category");

which will return your JSONArray or null if it is not a valid JSONArray .

Ovidiu Latcu
  • 71,607
  • 15
  • 76
  • 84
21

Even though you have got your answer, but still it can help other users...

 if (Law.get("LawSet") instanceof JSONObject)
 {
    JSONObject Lawset = Law.getJSONObject("LawSet");                        
 }
 else if (Law.get("LawSet") instanceof JSONArray)
{
    JSONArray Lawset = Law.getJSONArray("LawSet");
}

Here Law is other JSONObject and LawSet is the key which you want to find as JSONObject or JSONArray.

Vikas Gupta
  • 1,530
  • 5
  • 21
  • 34
10
String data = "{ ... }";
Object json = new JSONTokener(data).nextValue();
if (json instanceof JSONObject)
  //you have an object
else if (json instanceof JSONArray)
  //you have an array

tokenizer is able to return more types: http://developer.android.com/reference/org/json/JSONTokener.html#nextValue()

neworld
  • 7,757
  • 3
  • 39
  • 61
0
           if (element instanceof JSONObject) {

                Map<String, Object> map = json2Java.getMap(element
                        .toString());
                if (logger.isDebugEnabled()) {
                    logger.debug("Key=" + key + " JSONObject, Values="
                            + element);
                }
                for (Entry<String, Object> entry : map.entrySet()) {
                    if (logger.isDebugEnabled()) {
                        logger.debug(entry.getKey() + "/"
                                + entry.getValue());
                    }
                    jsonMap.put(entry.getKey(), entry.getValue());
                }
            }
Anand
  • 1,845
  • 2
  • 20
  • 25
-1

You can use instanceof to check the type of the result that you get. Then you can handle it as you wish.

Dimitris Makris
  • 5,183
  • 2
  • 34
  • 54