Foreach with JSONArray and JSONObject

后端 未结 3 1483
后悔当初
后悔当初 2020-12-14 16:07

I\'m using org.json.simple.JSONArray and org.json.simple.JSONObject. I know that these two classes JSONArray and JSONObject

相关标签:
3条回答
  • 2020-12-14 16:10

    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.

    0 讨论(0)
  • 2020-12-14 16:31

    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"}
    
    0 讨论(0)
  • 2020-12-14 16:33

    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

    0 讨论(0)
提交回复
热议问题