46

I'm using org.json.simple.JSONArray and org.json.simple.JSONObject. I know that these two classes JSONArray and JSONObject are incompatible, but still I want to do quite a natural thing - I want to for-each over JSONArray parsing at each iteration step one JSONObject (nested inside that JSONArray). I try to do it like so:

JSONArray arr = ...; // <-- got by some procedure
for(JSONObject o: arr){
    parse(o);
}

When I try to compile this code, indeed I get "incompatible types" error, even though it looks so natural. So, my question is what is the best way to iterate through JSONArray?

Jacobian
  • 10,122
  • 29
  • 128
  • 221

4 Answers4

71

Seems like you can't iterate through JSONArray with a for each. You can loop through your JSONArray like this:

for (int i=0; i < arr.length(); i++) {
    arr.getJSONObject(i);
}

Source

Community
  • 1
  • 1
dguay
  • 1,635
  • 15
  • 24
52

Apparently, org.json.simple.JSONArray implements a raw Iterator. This means that each element is considered to be an Object. You can try to cast:

for(Object o: arr){
    if ( o instanceof JSONObject ) {
        parse((JSONObject)o);
    }
}

This is how things were done back in Java 1.4 and earlier.

RealSkeptic
  • 33,993
  • 7
  • 53
  • 79
  • 1
    Thanks! It works. Though, it seems like I did it using `java.util.Iterator` – Jacobian Oct 19 '15 at 13:35
  • 2
    @Jacobian Yes, it's `java.util.Iterator`, but it's a *raw* one (E.g. a `List` would return an `Iterator`, and then you can use `String` as the enhanced for loop variable's type. When it's raw, the base type is assumed to be `Object`. – RealSkeptic Oct 19 '15 at 13:39
39

Make sure you are using this org.json: https://mvnrepository.com/artifact/org.json/json

if you are using Java 8 then you can use

import org.json.JSONArray;
import org.json.JSONObject;

JSONArray array = ...;

array.forEach(item -> {
    JSONObject obj = (JSONObject) item;
    parse(obj);
});

Just added a simple test to prove that it works:

Add the following dependency into your pom.xml file (To prove that it works, I have used the old jar which was there when I have posted this answer)

<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20160810</version>
</dependency>

And the simple test code snippet will be:

import org.json.JSONArray;
import org.json.JSONObject;

public class Test {
    public static void main(String args[]) {
        JSONArray array = new JSONArray();

        JSONObject object = new JSONObject();
        object.put("key1", "value1");

        array.put(object);

        array.forEach(item -> {
            System.out.println(item.toString());
        });
    }
}

output:

{"key1":"value1"}
yanike
  • 827
  • 3
  • 13
  • 29
Prasad Khode
  • 6,602
  • 11
  • 44
  • 59
  • can achieve the same if using [retrolambda](http://www.vogella.com/tutorials/Retrolambda/article.html) with java 7 – Fonix Aug 25 '17 at 09:42
  • 3
    The method forEach(( item) -> {}) is undefined for the type JSONArray – Prakhyat Nov 17 '17 at 04:17
  • 2
    @Jugi the json library that I have used above is `org.json` and you can use `forEach` on `JSONArray`, you can check once if you are still in doubt – Prasad Khode Nov 13 '18 at 06:00
  • 1
    I beg to differ with Jugi and akcasoy. This works for me with Java 8 and org.json.JSONArray. – FlyingSheep May 14 '19 at 19:19
  • 1
    This works with org.json here -> https://mvnrepository.com/artifact/org.json/json Make sure you aren't using the wrong org.json – yanike Dec 20 '19 at 16:18
  • Also note that forEach() doesn't give you all the options a true Iterator will give. For more features, use the following: Iterator> arrayi = arrayJson.iterator(); while (arrayi.hasNext()) { JSONObject obj = (JSONObject) arrayi.next(); } – yanike Dec 20 '19 at 16:39
2
  • Inside the for loop, you can simply typecast Object to JSONObject and access the values.

Eg:

    JSONArray myJSONArray = [...Some JSONObjects Here...];

    for (Object myObject : myJSONArray) {

        //If you want to get JSONObject
        JSONObject myJSONObject = (JSONObject) myObject;

        //If you want to access JSONObject's values
        long number     = myJSONObject.getLong("myNum");
        String myString = myJSONObject.getString("myStr");
    }
Sivaraman
  • 168
  • 1
  • 7