My app receives a JSON response from web services and processes the data. The response that is received could have any number of objects. My normal method of parsing is:
JSONObject jsonObj = new JSONObject(json);
JSONArray arrChanges = jsonObj.getJSONObject("Changes").getJSONArray("Row");
for (int i = 0; i < arrChanges.length(); i++)
{
// do stuff
}
This normally gets the array Row
inside the object Changes
, and works fine. However, I tested it with only one record being returned, and suddenly got the error: JSONObject cannot be converted to JSONArray
. After looking at the json, I can see that because there is now only one object, it is no longer a JSONArray
, it is now just a JSONObject
. Meaning that trying to use getJSONArray
will obviously fail.
So my question is; considering I will receive a varying number of items (0 to lots), how can I reliably parse this data (without knowing how many records it will have)?