Kevin Bradshaw Kevin Bradshaw - 6 months ago 60
JSON Question

JSON Array iteration in Android/Java

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

I have done it two different ways,

1.) make a Map

        HashMap<String, String> applicationSettings = new HashMap<String,String>();
        for(int i = 0; i < settings.length(); i++){
            String value = settings.getJSONObject(i).getString("value");
            String name = settings.getJSONObject(i).getString("name");
            applicationSettings.put(name, value);
        }

2.) make a JSONArray of names

    JSONArray names= json.names();
    JSONArray values = json.toJSONArray(names);
    for(int i = 0 ; i < values.length(); i++){
        if(names.getString(i).equals("description")){
            setDescription(values.getString(i));
        }
        else if(names.getString(i).equals("expiryDate")){
            String dateString = values.getString(i);
            setExpiryDate(stringToDateHelper(dateString)); 
        }
        else if(names.getString(i).equals("id")){
            setId(values.getLong(i));
        }
        else if(names.getString(i).equals("offerCode")){
            setOfferCode(values.getString(i));
        }
        else if(names.getString(i).equals("startDate")){
            String dateString = values.getString(i);
            setStartDate(stringToDateHelper(dateString));
        }
        else if(names.getString(i).equals("title")){
            setTitle(values.getString(i));
        }
    }
Comments