Foreach with JSONArray and JSONObject

后端 未结 3 1482
后悔当初
后悔当初 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: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)

    
        org.json
        json
        20160810
    
    

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

提交回复
热议问题