JAVA JSONArray遍历方法

1、使用for循环进行遍历,直接上代码吧:

    /**
     * 遍历JSONArray
     */
    private static void LoopJSONArray(){
        //颜色数组字符串
        String colorStr = "[{'name':'刘德华','age':28,'sex':'男'}," + 
                           "{'name':'张学友','age':29,'sex':'男'}]";
        //转化为数组
        JSONArray jsonArr = JSONArray.fromObject(colorStr); 

        for (int i = 0; i < jsonArr.size(); i++) {
            JSONObject jsonObject = jsonArr.getJSONObject(i);
            String name = jsonObject.getString("name");
            Integer age = (Integer) jsonObject.get("age");
            System.out.println("name:"+name+";age:"+age);
        }
    }

输出结果:

name:刘德华;age:28
name:张学友;age:29

2、使用Iterator进行遍历,也是直接上代码:

 /**
     * 遍历JSONArray
     */
    private static void LoopJSONArray(){
    //颜色数组字符串
    String colorStr = "[{'name':'刘德华','age':28,'sex':'男'}," + 
                       "{'name':'张学友','age':29,'sex':'男'}]";
    //转化为数组
    JSONArray jsonArr = JSONArray.fromObject(colorStr); 

    Iterator it   = jsonArr.iterator();
    List list = new ArrayList();
    while (it.hasNext()) {
    JSONObject jsonObj = (JSONObject) it.next();
        String name = jsonObj.getString("name");
        Integer age = (Integer) jsonObj.get("age");
        System.out.println("name:"+name+";age:"+age);          
    }
}
 
 

输出结果:

name:刘德华;age:28
name:张学友;age:29

你可能感兴趣的:(JAVA JSONArray遍历方法)