Android:从JSON动态获取JSON数组键名

问题描述 投票:0回答:5

我有一个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"
}],

}

我需要的是,我想动态获取所有关键名称,如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();
                }
            }
        }

我得到了存储在String键中的所有键名。但是我无法打开获取JSON数组中的值,例如。我需要使用String(Key)获取第一个和第二个数组中的值。我怎样才能做到这一点。???

java android arrays json android-json
5个回答
8
投票

首先,要获取键名,您可以轻松地遍历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) 
    }

0
投票

这样的事情将允许您在使用已完成的工具提取密钥后迭代数组和单个字段。而不是“类型”使用您将在此之前创建的键变量。

JSONArray allDetails = response.getJsonArray("All_Details")

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

0
投票

如果你想从response JSONObject获取JSON数组,你可以使用JSONArray classJSONObject有一种获得JSONArray的方法:getJSONArray(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();
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.