156

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.

Svetoslav Marinov
  • 1,498
  • 14
  • 11
Kevin Bradshaw
  • 6,327
  • 13
  • 55
  • 78
  • 1
    check out following link: https://androidbeasts.wordpress.com/2015/08/04/json-parsing-tutorial/ – Aakash Aug 05 '15 at 15:57

9 Answers9

348

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?

vipw
  • 7,593
  • 4
  • 25
  • 48
  • 5
    note that if you send an "array" that doesn't have consecutive numbers, you have to use JSONObject – max4ever Jun 29 '12 at 14:52
  • yeah it perfect but while large amount of data its being very slow in processing :( – Ahmad Arslan Aug 04 '14 at 10:15
  • @ArslanAhmad If you have a large amount of data, you don't want to construct the entire json object array in memory. Instead use a SAX-like approach. See here: http://stackoverflow.com/questions/10657725/parser-for-json-in-servlet-just-like-sax-for-xml – vipw Aug 04 '14 at 14:26
  • this doesnt work for me. i get a JSON Exception because of the "{" bracket surrounding the object ? – filthy_wizard Dec 03 '15 at 11:06
69

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));
        }
    }
slinden77
  • 3,378
  • 2
  • 37
  • 35
Nathan Schwermann
  • 31,285
  • 16
  • 80
  • 91
7

Unfortunately , JSONArray doesn't support foreach statements, like:

for(JSONObject someObj : someJsonArray) {
    // do something about someObj
    ....
    ....
}
Ivan86
  • 5,695
  • 2
  • 14
  • 30
Dream
  • 103
  • 1
  • 1
5

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:

int myJsonArraySize = myJsonArray.size();

for (int i = 0; i < myJsonArraySize; i++) {
    JSONObject myJsonObject = (JSONObject) myJsonArray.get(i);

    // Do whatever you have to do to myJsonObject...
}
Graham S.
  • 1,480
  • 1
  • 20
  • 28
3

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:

@Override
public Iterator iterator() {
    return this.myArrayList.iterator();
}

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.

Thunderforge
  • 19,637
  • 18
  • 83
  • 130
  • 1
    What's interesting is that at one time the JSON.org implementation had an Iterator in the JSONArray class, but they removed it: https://github.com/douglascrockford/JSON-java/commit/ae8d12c5f4c139d310bf6fee39c35b215d2fec15 – vipw Aug 08 '14 at 11:08
  • 1
    @vipw I had e-mailed them once about implementing Iterable, but they said that ultimately they couldn't because it would break compatibility with Java 1.4. Perhaps that was why it was removed in the commit. – Thunderforge Aug 08 '14 at 14:11
3

On Arrays, look for:

JSONArray menuitemArray = popupObject.getJSONArray("menuitem"); 
yivi
  • 42,438
  • 18
  • 116
  • 138
Paul Burke
  • 25,496
  • 9
  • 66
  • 62
2

You are using the same Cast object for every entry. On each iteration you just changed the same object instead creating a new one.

This code should fix it:

JSONArray jCastArr = jObj.getJSONArray("abridged_cast");
ArrayList<Cast> castList= new ArrayList<Cast>();

for (int i=0; i < jCastArr.length(); i++) {
    Cast person = new Cast();  // create a new object here
    JSONObject jpersonObj = jCastArr.getJSONObject(i);

    person.castId = (String) jpersonObj.getString("id");
    person.castFullName = (String) jpersonObj.getString("name");

    castList.add(person);
}
details.castList = castList;
Andriya
  • 241
  • 2
  • 14
1

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:

s[i] = array.isNull(i) ? null : array.getString(i);
18446744073709551615
  • 16,368
  • 4
  • 94
  • 127
0

Alternatively, especially on Android where there is no iterator(), you could define your own iterator :

import java.util.Iterator;
import org.json.JSONArray;
import org.json.JSONException;

public final
class JSONArrayIterator<E> implements Iterator<E> {
    private JSONArray jsonArray;
    private int l;
    private int i;

    JSONArrayIterator(JSONArray jsonArray) {
        this.jsonArray = jsonArray;
        this.l = jsonArray.length();
        this.i = 0;
    }
    @SuppressWarnings("unchecked")
    public E next() {
        try {
            Object o = this.jsonArray.get(this.i++);
            return (E)o;
        } catch (JSONException ex) {
        }
        return null;
    }

}

It works when you assume the element types of your array are all the same. This might not be considered a good practice in many cases, so you might want to add more type-checking.

But then you can then use :

for (JSONObject row: new JSONArrayIterator<JSONObject>(jsonArray)){
     id = row.getInt("id");
     name = row.getString("name");
     password = row.getString("password");
}
FredG
  • 712
  • 7
  • 10