获取对象JSON Java Android中的所有对象

xcv*_*vbn 0 android json-api

因此,我试图使用返回JSON响应的英雄联盟API.我没有使用像Jakcson或GSON这样的花哨的lib,

{"type":"champion","version":"5.11.1","data":{"Thresh":{"id":412,"key":"Thresh","name":"Thresh","title":"the Chain Warden"},"Aatrox":{"id":266,"key":"Aatrox","name":"Aatrox","title":"the Darkin Blade"},"Tryndamere":{"id":23,"key":"Tryndamere","name":"Tryndamere","title":"the Barbarian King"},"Gragas":{"id":79,"key":"Gragas","name":"Gragas","title":"the Rabble Rouser"}}}
Run Code Online (Sandbox Code Playgroud)

但是当我尝试访问数据对象中的对象时,我必须明确列出代码中的键名.

关键名称真的很动态,所以它不实用.

有没有办法在没有显式调用键名的情况下获取数据对象中的所有对象?

这是我的Java客户端代码

public String callApi(String API_URL) throws IOException {

    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);

    OkHttpClient client = new OkHttpClient();
    Request request = new Request.Builder()
            .url(API_URL)
            .build();

    Response response = client.newCall(request).execute();
    return response.body().string();
}

public void buttonClick(View view) throws IOException, JSONException {

    String API_URL = "https://global.api.pvp.net/api/lol/static-data/tr/v1.2/champion?locale=en_US&api_key=my_key_here";

    String champions_json = callApi(API_URL);

    Log.i("summoner",champions_json);

    JSONObject json= new JSONObject(champions_json);
    JSONObject data = json.getJSONObject("data");

    Log.i("summoner", String.valueOf(data));

    List<String> champions = new ArrayList<String>();
    champions.add("Garen");
    champions.add("Aatrox");
    champions.add("Thresh");

    for (String champion : champions) {
        JSONObject object = new JSONObject(String.valueOf(data));
        String name = object.getString(champion);
        Log.i("summoner",name);
    }
}
Run Code Online (Sandbox Code Playgroud)

Ebo*_*bob 6

获取JSON对象的键keys(),然后迭代它们.

Iterator<String> keys = json.keys();

while (keys.hasNext())
{
    // Get the key
    String key = keys.next();

    // Get the value
    JSONObject value = json.getJSONObject(key);

    // Do something...
}
Run Code Online (Sandbox Code Playgroud)