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.
unfortunately , JSONArray doesn't support for each statement, like:
While iterating over a JSON array (org.json.JSONArray, built into Android), watch out for null objects; for example, you may get
"null"
instead of a null string.A check may look like:
When I tried @vipw's suggestion, I was faced with this exception:
The method getJSONObject(int) is undefined for the type JSONArray
This worked for me instead:
If you're using the JSON.org Java implementation, which is open source, you can just make JSONArray implement the
Iterable
interface and add the following method to the class:This will make all instances of JSONArray iterable, meaning that the
for (Object foo : bar)
syntax will now work with it (note that foo has to be an Object, because JSONArrays do not have a declared type). All this works because the JSONArray class is backed by a simple ArrayList, which is already iterable. I imagine that other open source implementations would be just as easy to change.I have done it two different ways,
1.) make a Map
2.) make a JSONArray of names
I think this code is short and clear:
Is that what you were looking for?