Reputation: 1418
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"));
}
}
}
}
}
Upvotes: 1
Views: 1065
Reputation: 1
This works for JavaScript and very simple.
//mArray is your json array
let newArray = JSON.stringify(mArray);
mArray = JSON.parse(newArray);
Upvotes: 0
Reputation: 1824
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
Upvotes: 1
Reputation: 1500185
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"));
}
}
Upvotes: 2
Reputation: 48404
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()
.
Upvotes: 1