android – JSON Java check element is a JSONArray or JSONObject-ThrowExceptions

Exception or error:

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.

How to solve:

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 .

###

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.

###

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

###

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

###

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

Leave a Reply

Your email address will not be published. Required fields are marked *