Accessing members of items in a JSONArray with Java

后端 未结 6 1568
小蘑菇
小蘑菇 2020-11-22 16:23

I\'m just getting started with using json with java. I\'m not sure how to access string values within a JSONArray. For instance, my json looks like this:

{
         


        
6条回答
  •  耶瑟儿~
    2020-11-22 16:50

    Java 8 is in the market after almost 2 decades, following is the way to iterate org.json.JSONArray with java8 Stream API.

    import org.json.JSONArray;
    import org.json.JSONObject;
    
    @Test
    public void access_org_JsonArray() {
        //Given: array
        JSONArray jsonArray = new JSONArray(Arrays.asList(new JSONObject(
                        new HashMap() {{
                            put("a", 100);
                            put("b", 200);
                        }}
                ),
                new JSONObject(
                        new HashMap() {{
                            put("a", 300);
                            put("b", 400);
                        }}
                )));
    
        //Then: convert to List
        List jsonItems = IntStream.range(0, jsonArray.length())
                .mapToObj(index -> (JSONObject) jsonArray.get(index))
                .collect(Collectors.toList());
    
        // you can access the array elements now
        jsonItems.forEach(arrayElement -> System.out.println(arrayElement.get("a")));
        // prints 100, 300
    }
    

    If the iteration is only one time, (no need to .collect)

        IntStream.range(0, jsonArray.length())
                .mapToObj(index -> (JSONObject) jsonArray.get(index))
                .forEach(item -> {
                   System.out.println(item);
                });
    

提交回复
热议问题