0

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

Mike Baxter
  • 6,868
  • 17
  • 67
  • 115

3 Answers3

0

Force your json to be an array on the client side.

EDIT: I said client, I just mean wherever you are creating it.

var json = [];

json.push({"yourdataname":"yourdatavalue"});
  • I'd agree that the data should be forced to be an array when the json is created, even if the array only contains one item, you need some structure. – darnmason May 19 '14 at 16:06
  • This is my ideal solution but I'm afraid I don't really understand how this code converts a JSONObject to a JSONArray. – Mike Baxter May 22 '14 at 11:24
  • Your array needs to an array, weather it has 1 item or 1000, not an n sized collection of objects. force it to be like {"Row":[{},{}]} I hope that helps. I'm not an expert, but I had a similar issue once. – user3608828 May 22 '14 at 21:22
0

Try editing parsing with the help of this concept

if (<your jsonobject> instanceof JSONArray)
 {
  //parse as an jsonarray
  for(....;....;...){
 //your logic
 }
 }
 else{
 //parse as jsonobject without using any index value
 }

hope this help you with your problem.

ajitksharma
  • 4,523
  • 2
  • 21
  • 40
0

Just another way to do it:

try{
JSONArray arrChanges = jsonObj.getJSONObject("Changes").getJSONArray("Row");
for (int i = 0; i < arrChanges.length(); i++)
{
    // do stuff
}
}catch(JSONException e){
//i assume that the actual data is json array if not this block is called try jsonobject parsing here 
// its something like try catch inside try catch
}
Illegal Argument
  • 10,090
  • 2
  • 44
  • 61