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"));
}
}
}
}
}
-
1Your JSON response has this structure. Array(Object(Array(Object)) What your'e doing is, Array(Array(Object))siriscac– siriscac2015年06月04日 14:35:38 +00:00Commented Jun 4, 2015 at 14:35
-
I purpose you model your JSON using a POJO, and then let something like Gson parse it for you. It seems like your model would be quite simple, and this would also drastically reduce the cyclomatic complexity of your code.user489041– user4890412015年06月04日 14:51:55 +00:00Commented Jun 4, 2015 at 14:51
4 Answers 4
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"));
}
}
Comments
The second level of your JSON consists in your JSON array elements.
What you need, as you already mention, is to get them as JSONObject.
Then you getJSONArray from that object:
//download json array
for (int i = 0; i < mArray.length(); i++) {
if(mArray != null) {
JSONObject element = mArray.getJSONObject(i);
JSONArray list = element.getJSONArray("Header1");
if(list != null) {
However, since the "Header..." keys are changing, you might need to infer the key by invoking keys().
Comments
A much easier way for you to handle this would be to use GSON library and create POJO class to resemble ur JSON here is a nice website to do that
Comments
This works for JavaScript and very simple.
//mArray is your json array
let newArray = JSON.stringify(mArray);
mArray = JSON.parse(newArray);