JSONObject和JSONArray的关系

JSON字符串的最上一层,肯定是一个JSONObject,JSONObject的下一层,可以包含JSONArray,JSONArray又包含了若干个JSONObject。用例子来说明:

package myJson;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class myJson {
    
    static String jsonString = new String("{'Data':[{'Id':1,'Studentid':'0001','Name':'张三'}," +
            "{'Id':2,'Studentid':'0002','Name':'李四'}," +
            "{'Id':3,'Studentid':'0003','Name':'王五'}]}");
    
    public static void main(String args[]){
        JSONObject jsonObject = JSONObject.fromObject(jsonString);
        JSONArray jsonArray = jsonObject.getJSONArray("Data");
        JSONObject jsonObject2;
        for (int i = 0; i < jsonArray.size(); i++){
            jsonObject2 = (JSONObject) jsonArray.get(i);
            System.out.println(String.valueOf(i) + ":" + jsonObject2.toString());
        }
    }

}

以上代码,先获得了一个JSONObject,然后根据这个JSONObject获得了"Data"这个JSONArray,然后从JSONArray里面获得了三个JSONObject。运行结果如下:

原文地址:https://www.cnblogs.com/mstk/p/5179178.html