Android JSON 对象获取

Android JSON object fetch

我无法从此 api 获取数据。我可以请求数据的第一部分,但在 "quotes" 之后我无法获取数据,我需要获取价格。

JSON 示例

{
"data": {
    "1": {
        "id": 1, 
        "name": "Bitcoin", 
        "symbol": "BTC", 
        "website_slug": "bitcoin", 
        "rank": 1, 
        "circulating_supply": 17008162.0, 
        "total_supply": 17008162.0, 
        "max_supply": 21000000.0, 
        "quotes": {
            "USD": {
                "price": 9024.09, 
                "volume_24h": 8765400000.0, 
                "market_cap": 153483184623.0, 
                "percent_change_1h": -2.31, 
                "percent_change_24h": -4.18, 
                "percent_change_7d": -0.47
            }
        }, 
        "last_updated": 1525137271
    }, 

请求代码

try {

    JSONObject jsonObject = response.getJSONObject("data");
    JSONArray jsonArray = jsonObject.names();
    Log.e(TAG,jsonArray.toString());
    for(int i=0;i<jsonArray.length();i++){

        JSONObject getObjectFromJsonArray=jsonObject.getJSONObject(jsonArray.getString(i));
        CoinMarketAPI coin=new CoinMarketAPI();

        coin.setId(getObjectFromJsonArray.getString("id"));
        coin.setName(getObjectFromJsonArray.getString("name"));
        coin.setSymbol(getObjectFromJsonArray.getString("symbol"));
        coin.setWebsite_slug(getObjectFromJsonArray.getString("website_slug"));
        coin.setRank(getObjectFromJsonArray.getString("rank"));
        coin.setCirculating_supply(getObjectFromJsonArray.getString("circulating_supply"));
        coin.setTotal_supply(getObjectFromJsonArray.getString("total_supply"));
        coin.setQuotes(getObjectFromJsonArray.getString("quotes"));

        if (jsonObject.has("price")){coin.setPrice(getObjectFromJsonArray.getString("price"));
        }else{
            Log.d(TAG, "No price");
        }

        firstlist.add(coin);
    }
}

注意

我将硬币放在 if 语句中以查看发生了什么我得到的日志输出是 "no price"

所以出于某种原因,我的代码认为价格中没有数据?

您没有正确查找 "price"。您的 if 语句正在寻找 "data" 下的价格,它需要在 "USD".

下寻找价格

你应该这样做

JSONObject usd = getObjectFromJsonArray.getJSONObject("quotes").getJSONObject("USD");

if (usd.has("price")){
    coin.setPrice(usd.getDouble("price"));
}else{
    Log.d(TAG, "No price");
}