簡體   English   中英

為什么在 JsonArray 中使用 JSONObject 時需要顯式類型轉換?

[英]why should I need Explicit Type Conversion When Using JSONObject inside JsonArray?

我收到來自 RestApi 的 JsonArray 響應。

它看起來像這樣。

[{"symbol":"BTC","volumeUsd24Hr":"9933608358.6769638763447470","marketCapUsd":"373762242595.8886412421003192","priceUsd":"19494.3435967958368457","vwap24Hr":"19703.2611157615056124","changePercent24Hr":"-2.4906058989768847" "name":"Bitcoin","explorer":"https://blockchain.info/","rank":"1","id":"bitcoin","maxSupply":"21000000.0000000000000000","supply ":"19172856.0000000000000000"},{"symbol":"ETH","volumeUsd24Hr":"3241023190.3730390178381998","marketCapUsd":"163079674691.9858451324912645","priceUsd":"1329.0704167150164988","vwap24Hr":"1337.1800236177182353","changePercent24Hr ":"-2.1575264116384809","name":"Ethereum","explorer":"https://etherscan.io/","rank":"2","id":"ethereum","maxSupply": null,"supply":"122702057.4990000000000000"},{"symbol":"USDT","volumeUsd24Hr":"13840788061.6519189957942816","marketCapUsd":"68364449761.2046855857488307","priceUsd":"1.0004593774481033","vwap24Hr":"1.0004839031623615 ","changePercent24Hr":"0.0536998153626522","name":"Tether","explorer":"https:// www.omniexplorer.info/asset/31","rank":"3","id":"tether","maxSupply":null,"supply":"68333059094.8965800000000000"},{"symbol"...

JsonObject里面有JsonArrays。

我想從每個 JsonObject(symbol) 中提取值。

所以我通過打印 jsonArray.get(0).getClass() 檢查了 JsonObject 的數據類型,它按預期給了我“class org.json.simple.JSONObject”。

所以我試圖通過使用來提取價值

        jsonArray.get(0).get("symbol");

但是此代碼會導致編譯錯誤,提示“無法解析‘Object’中的‘get’方法”

所以我需要像這樣將數據類型顯式轉換為 JSONObject

((JSONObject) jsonArray.get(0)).get("symbol")

然后我得到了我想要的。

我想知道的是,為什么我應該明確地將 jsonArray.get(0) 轉換為 JSONObject,

即使.getclass() 說數據的類型是 JSONObject

這是我的完整代碼..提前致謝!

public static void main(String[] args) throws IOException, ParseException {
        OkHttpClient client = new OkHttpClient();
        MediaType mediaType = MediaType.parse("text/plain");
        Request request = new Request.Builder()
                .url("http://api.coincap.io/v2/assets")
                .get()
                .build();

        Response response = client.newCall(request).execute();

        JSONParser jsonParser = new JSONParser();
        Object obj = jsonParser.parse(response.body().string());

        JSONArray jsonArray = (JSONArray) ((JSONObject) obj).get("data");
        // JSONObject inside JSONArray

        System.out.println(jsonArray.get(0).getClass());
        
        System.out.println(((JSONObject) jsonArray.get(0)).get("symbol"));

    }

也許你可以試試

jsonArray.getJSONObject(0);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM