I'm getting a JsonArray response from RestApi.
it looks like this.
[{"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"...
There are JsonArrays inside JsonObject.
And I wanna extract values from Each JsonObject(symbol).
So I checked the data type of JsonObject by printing jsonArray.get(0).getClass(), and it gives me "class org.json.simple.JSONObject" as expected.
so I tried to extract value by using
jsonArray.get(0).get("symbol");
but this code makes compile error saying " Cannot resolve method 'get' in 'Object' "
So I needed to explicitly convert data type into JSONObject like this
((JSONObject) jsonArray.get(0)).get("symbol")
then I got what I want.
What I'm wondering is that why should I explicitly convert jsonArray.get(0) to JSONObject,
even though .getclass() says that the type of data is JSONObject
Here are my Full Code .. Thanks in advance!!
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"));
}
CodePudding user response:
Maybe you can try it
jsonArray.getJSONObject(0);