49

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?

4 Answers 4

74

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

Sign up to request clarification or add additional context in comments.

7 Comments

Unfortunatelly, it seems like JSONArray from org.json.simple.* does not have length() method and getJSONObject()
@Jacobian Have you tried using org.json.JSONArray?
Now, I have not tried it, yet. Is it much more powerful?
@Jacobian I found this
For org.json.simple.JSONArray you need to use the size() method (instead of length()) inherited from java.util.ArrayList.
|
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.

2 Comments

Thanks! It works. Though, it seems like I did it using java.util.Iterator
@Jacobian Yes, it's java.util.Iterator, but it's a raw one (E.g. a List<String> would return an Iterator<String>, 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.
40

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"}

6 Comments

can achieve the same if using retrolambda with java 7
The method forEach((<no type> item) -> {}) is undefined for the type JSONArray
@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
I beg to differ with Jugi and akcasoy. This works for me with Java 8 and org.json.JSONArray.
This works with org.json here -> mvnrepository.com/artifact/org.json/json Make sure you aren't using the wrong org.json
|
3
  • 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");
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.