Enc*_*rer 0 java arrays android json android-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"
}],
Run Code Online (Sandbox Code Playgroud)
}
我需要的是,我想动态获取所有关键名称,如status,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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
我得到了存储在String键中的所有键名.但是我无法打开获取JSON数组中的值,例如.我需要使用String(Key)获取第一个和第二个数组中的值.我怎样才能做到这一点.???
首先,要获取键名,您可以轻松地遍历JSONObject本身,如下所述:
Iterator<?> keys = response.keys();
while( keys.hasNext() ) {
String key = (String)keys.next();
if ( response.get(key) instanceof JSONObject ) {
System.out.println(key); // do whatever you want with it
}
}
Run Code Online (Sandbox Code Playgroud)
然后,获取数组的值:
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)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7061 次 |
| 最近记录: |