2016-03-08 120 views
0

我有一個JSON鏈接,如果我們打開它,我得到以下結果安卓:動態獲取JSON數組的鍵名從JSON

{ 
"Status": "Success", 

"All_Details": [{ 
    "Types": "0", 
    "TotalPoints": "0", 
    "ExpiringToday": 0 
}], 
"First": [{ 
    "id": "0", 
    "ImagePath": "http://first.example.png" 
}], 
"Second": [{ 
    "id": "2", 
    "ImagePath": "http://second.example.png" 
}], 
"Third": [{ 
    "id": "3", 
    "ImagePath": "http://third.example.png" 
}], 

}

我需要的是,我要動態獲取所有的關鍵名稱,如狀態,All_details,First等。

而且我還想獲​​取All_details和First Array中的數據。 我用下面的方法

@Override 
     public void onResponse(JSONObject response) throws JSONException { 
      VolleyLog.d(TAG, "Home Central OnResponse: " + response); 

      String statusStr = response.getString("Status"); 
      Log.d(TAG, "Status: " + statusStr); 

      if (statusStr.equalsIgnoreCase("Success")) { 
       Iterator iterator = response.keys(); 
       while (iterator.hasNext()) { 
        String key = (String)iterator.next(); 
       } 
      } 
     } 

我得到得到所有的鍵名存儲在字符串鍵。但我無法打開獲取JSON數組內的值,例如。我需要使用String(Key)來獲取第一個和第二個數組中的值。我怎樣才能做到這一點。???

回答

5

首先,獲得鍵名,就可以很容易地通過的JSONObject本身as mentioned here迭代:

Iterator<?> keys = response.keys(); 
while(keys.hasNext()) { 
    String key = (String)keys.next(); 
    if (jObject.get(key) instanceof JSONObject) { 
     System.out.println(key); // do whatever you want with it 
    } 
} 

然後,得到數組的值:

JSONArray arr = response.getJSONArray(key); 
    JSONObject element; 
    for(int i = 0; i < arr.length(); i++){ 
     element = arr.getJSONObject(i); // which for example will be Types,TotalPoints,ExpiringToday in the case of the first array(All_Details) 
    } 
+0

非常感謝...其工作... – IndependentDev

+0

@IndependentDev不客氣,很高興我可以幫助你:) –

0

這樣的事情可以讓你迭代陣列和單個字段,一旦你使用你已經完成的操作來提取密鑰。而不是「類型」使用您將在此之前創建的關鍵變量。

JSONArray allDetails = response.getJsonArray("All_Details") 

for (int i = 0 ; i < allDetails.length(); i++) { 
    JSONObject allDetail = allDetails.getJSONObject(i); 
    allDetails.getString("Types"); 
} 
+0

我不需要這個方法。我想動態獲取數組名稱(例如:All_details)並使用它我想動態獲取該數組中的值。 – IndependentDev

0

如果您想要從response JSONObject中獲取JSON數組,您可以使用JSONArray classJSONObject有一個獲得JSONArraygetJSONArray(String)的方法。請記住在嘗試此操作時趕上JSONException。例如,如果沒有密鑰,則會拋出此異常。

你的代碼可能看起來像這樣(只while循環):

while (iterator.hasNext()) { 
    String key = (String)iterator.next(); 
    try { 
     JSONArray array = response.getJSONArray(key); 
     // do some stuff with the array content 
    } catch(JSONException e) { 
     // handle the exception. 
    } 
} 

您可以用JSONArray方法數組獲取值(請參閱文檔)

0

首先我的想告訴你,這不是一個有效的JSON。刪除最後的逗號(,)使其有效。

然後可以遍歷喜歡這裏

JSONArray myKeys = response.names(); 
0

試試這個

Iterator keys = jsonObject.keys(); 
    while (keys.hasNext()) { 
     try { 
      String dynamicKey = (String) keys.next();//Your dynamic key 
      JSONObject item = jsonObject.getJSONObject(dynamicKey);//Your json object for that dynamic key 
     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 
    }