Reputation: 1413
I am calling an api through the following code,
System.out.println("its running");
String realTimeData = "https://api.coindesk.com/v1/bpi/currentprice.json";
HttpURLConnection conn = (HttpURLConnection) urlObj.openConnection();
conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2");
conn.setRequestMethod("GET");
String inputline;
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null){
System.out.println(response.append(inputLine));
}
in.close();
where response
outputs the following Json output.
{"time":{"updated":"Mar 4, 2018 18:53:00 UTC","updatedISO":"2018-03-04T18:53:00+00:00","updateduk":"Mar 4, 2018 at 18:53 GMT"},"disclaimer":"This data was produced from the CoinDesk Bitcoin Price Index (USD). Non-USD currency data converted using hourly conversion rate from openexchangerates.org","chartName":"Bitcoin","bpi":{"USD":{"code":"USD","symbol":"$","rate":"11,333.4625","description":"United States Dollar","rate_float":11333.4625},"GBP":{"code":"GBP","symbol":"£","rate":"8,208.4869","description":"British Pound Sterling","rate_float":8208.4869},"EUR":{"code":"EUR","symbol":"€","rate":"9,200.3915","description":"Euro","rate_float":9200.3915}}}
I am trying to get the data through keys, using this code
JSONObject json = new JSONObject(response);
String rate = json.getString("time");
System.out.println("rate was "+rate);
Whenever I run the above snippet, I get a JsonObject {"time"} not found
. My conclusion is either I don't understand what is a "key" in the above json format. or the response
that CoinDesk spits out is not getting treated as Json in my code.
Upvotes: 1
Views: 10183
Reputation: 329
The "time" is key for another JSONObject. If you want retrieve USD rate from "time" object, try this:
JSONObject json = new JSONObject(response);
JSONObject bpi = json.getJSONObject("bpi");
JSONObject usd = bpi.getJSONOBJECT("USD");
String rate = usd.getString("rate");
System.out.println("rate was "+rate);
Further info: http://www.oracle.com/technetwork/articles/java/json-1973242.html You can check JSON structure easily at: https://jsonformatter.curiousconcept.com/ Hope I could help you!
Upvotes: 2
Reputation:
You're trying to get the field time
as a String. When it's not. It's a JSONObject.
Note also that you were not using the right constructor.
Here's what you should do instead:
JSONObject json = new JSONObject (response.toString ());
JSONObject oTime = json.getJSONObject ("time");
System.out.println("rate was " + oTime);
Upvotes: 4