JSON Array iteration in Android/Java

Kevin Bradshaw picture Kevin Bradshaw · Aug 4, 2010 · Viewed 217.5k times · Source

I am building an android app that needs to download and synchronise with an online database, I am sending my query from the app to a php page which returns the relevant rows from a database in JSON format.

can someone please tell me the best way to iterate through a JSON array?

I receive an array of objects:

[{json object},{json object},{json object}]

What is the simplest piece of code I could use to access the JSONObjects in the array?

EDIT: now that I think of it the method I used to iterate the loop was:

for (String row: json){
     id = row.getInt("id");
     name = row.getString("name");
     password = row.getString("password");
}

So I guess I had was somehow able to turn the returned Json into and iterable array. Any Ideas how I could achieve this?

I apologise for my vaguness but I had this working from an example I found on the web and have since been unable to find it.

Answer

vipw picture vipw · Jun 16, 2011

I think this code is short and clear:

int id;
String name;
JSONArray array = new JSONArray(string_of_json_array);
for (int i = 0; i < array.length(); i++) {
    JSONObject row = array.getJSONObject(i);
    id = row.getInt("id");
    name = row.getString("name");
}

Is that what you were looking for?