1. 程式人生 > >JSON學習(四):JsonArray和JsonObject遍歷方法

JSON學習(四):JsonArray和JsonObject遍歷方法

一:遍歷JsonArray

 // 一個未轉化的字串
String str = "[{name:'a',value:'aa'},{name:'b',value:'bb'},{name:'c',value:'cc'},{name:'d',value:'dd'}]" ; 
 // 首先把字串轉成 JSONArray  物件
JSONArray json = JSONArray.fromObject(str );
if(json.size()>0){
  for(int i=0;i<json.size();i++){
 // 遍歷 jsonarray 陣列,把每一個物件轉成 json 物件
JSONObject job = json.getJSONObject(i); 
// 得到 每個物件中的屬性值
System.out.println(job.get("name")+"=") ;  
  }
}

一:遍歷JsonObject

JSONObject jsonObject = new JSONObject(s);
//然後用Iterator迭代器遍歷取值,建議用反射機制解析到封裝好的物件中
JSONObject jsonObject = new JSONObject(jsonString);
        Iterator iterator = jsonObject.keys();
while(iterator.hasNext()){
            key = (String) iterator.next();
        value = jsonObject.getString(key);
}