I am receiving json and am trying to operate on it using the JSONObject and JSONArray classes. I have nested objects and need to determine if those nested objects are arrays or objects. The problem is that if I assume it is an object and it is actually an array, when I get call getJSONObject, an exception is raised. I'm wondering if the only way to do this is just to add try/catch blocks or if there is a better way to do this. For example, say I have:
{"key1": "val1",
"key2": {"level2": {"level3": "val3"}}
}
I may also have the level2 element with multiple values and coming in as an array:
{"key1": "val1",
"key2": {"level2": [{"level3": "val3"}]}
}
How would I extract the level2 object (as an object) and determine if it is an object or an array? Is the only way to really do this using string manipulation?
If I do something like:
jsonObj.getJSONObject("key2").getJSONObject("level2");
It will result in an error: "org.json.JSONException: JSONObject["level2"] is not a JSONObject and conversly, if I call getJSONArray("level2") and level2 is not an array I will get an error indicating it is not an array.