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.
Yes, this is because the
getJSONObject("category")will try to convert thatStringto a JSONObject what which will throw aJSONException. You should do the following:Check if that object is a
JSONObjectby using:which will return a
JSONObjectornullif thecategoryobject is not a json object.Then you do the following:
which will return your
JSONArrayor null if it is not a validJSONArray.