Android:从JSON动态获取JSON数组键名 [英] Android: Dynamically Get JSON Array Key Name From JSON

查看:635
本文介绍了Android:从JSON动态获取JSON数组键名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个json链接,如果打开它,我会得到以下结果

I have a json link, if we open it I get a following result

{
"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等.

What I need is, I want to dynamically get all the key names like status, All_details, First etc.

我也想在All_details和First Array中获取数据. 我使用了以下方法

And I also want to get the data inside the All_details and First Array. I used following method

@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)获取第一和第二个数组内的值.我该怎么做.

I get all the key names in get stored in the String key. But I am unable to open get the values inside the JSON array, for eg. I need to get the values inside first and second array using the String(Key). How can I do that.???

推荐答案

首先,要获取键名,您可以轻松地遍历JSONObject本身

First, to get the keynames, you can easily iterate through the JSONObject itself 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) 
    }

这篇关于Android:从JSON动态获取JSON数组键名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆