JSONArray Parsing error

I need help with parsing a JSON array.

[
    {
        "Header1": [
            {
                "path": "upload/images/1430572021716.jpg"
            },
            {
                "path": "upload/images/1430574003703.jpg"
            }
        ]
    },
    {
        "Header2": [
            {
                "path": "upload/images/1430574124119.jpg"
            },
            {
                "path": "upload/images/1430574203001.jpg"
            }
        ]
    }
]

I am receiving the above JSONArray perfectly. I want to iterate through the array and extract both the header text "Header1" and the value of path

I keep running into the following error message

at 0 of type org.json.jsonarray cannot be converted to jsonobject

after some research, this is due to the system not being able to parse to a JSON array. It does work if I change the "list" array to an objct, however this is not an array and i loose the ability to iterate through it.

Here is the code i tried to parse the array with

    JSONArray mArray;

    mArray = json;

    //download json array
    for (int i = 0; i < mArray.length(); i++) {
        if(mArray != null) {
            JSONArray list = mArray.getJSONArray(i);
            if(list != null) {
                for(int a = 0; a < list.length();a++) {
                    JSONObject elem = list.getJSONObject(a);
                    if (elem != null) {
                            listdata.add(elem.getString("path"));

                    }
                }
            }
        }
    }
Jon Skeet
people
quotationmark

You're trying to treat each element of the top-level array as another array - it's not, it's an object. That object then has another field whose value is an array. So you want something like:

for (int i = 0; i < json.length(); i++) {
    JSONObject container = json.getJSONObject(i);
    // We don't know the property name, but there's only one, apparently...
    String key = container.keys().next();
    JSONArray subarray  = container.getJSONArray(key);
    for (int j = 0; j < subarray.length(); j++) {
        listdata.add(subarray.getJSONObject(j).getString("path"));
    }
}

people

See more on this question at Stackoverflow