我有一个 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();
}
}
}
我将 get 中的所有键名称存储在 String 键中。但我无法打开获取 JSON 数组内的值,例如。我需要使用 String(Key) 获取第一个和第二个数组中的值。我怎样才能做到这一点。???
最佳答案
首先,要获取键名,您可以轻松地迭代 JSONObject 本身 as mentioned here :
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
}
}
然后,获取数组的值:
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)
}
关于java - Android:从 JSON 动态获取 JSON 数组键名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35865470/