Manuel Mena Rodríguez Manuel Mena Rodríguez - 5 months ago 57
Android Question

JSONObject to arraylist? Why this JSONException?

I have this json

{
"summary":
{
"total_count":2
},
"data":
[
{
"id":"129393910815742",
"name":"Mike Pollito"
},
{
"id":"117161088707629",
"name":"James Carballo"
}
],
"paging":
{
"cursors":
{
"after":"mUhn",
"before":"QVFn"
}
}
}


and I need to save the ids in an
ArrayList
or any simple array.

Note:The number of ids may vary.

The problem is than i can easily get "total_count" with

int amigos = listatodoslosamigos.getJSONObject("summary").getInt("total_count");


but when i try to get any "id" when i call

JSONObject data = listatodoslosamigos.getJSONObject("data");


i always get a JSONException

This is my buggy code

public void onCompleted(GraphResponse response) {
/* handle the result */
JSONObject listatodoslosamigos = response.getJSONObject();
try {
int amigos = listatodoslosamigos.getJSONObject("summary").getInt("total_count");
JSONObject data = listatodoslosamigos.getJSONObject("data");

} catch (JSONException e) {}
}
}
).executeAsync();

Answer

Your data property in the JSON is an array, so you need to use getJSONArray, for instance;

JSONArray data = listatodoslosamigos.getJSONArray("data");

You can iterator for a JSONArray using .listIterator() or via .getJSONObject(index);

JSONArray data = listatodoslosamigos.getJSONArray("data");
JSONObject member = data.getJSONObject(0);

You can also use JSONArray.toCollection and data.toArray to turn a JSONArray into a normal Java collection or array.

Comments