我通过以下代码调用api,
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();
其中response
输出以下Json输出。
{"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}}}
我正在尝试通过密钥获取数据,使用此代码
JSONObject json = new JSONObject(response);
String rate = json.getString("time");
System.out.println("rate was "+rate);
每当我运行上述代码段时,我都会得到JsonObject {"time"} not found
。我的结论要么是我不明白什么是"关键"以上json格式。或者CoinDesk吐出的response
在我的代码中没有被视为Json。
答案 0 :(得分:4)
您正在尝试将字段backgroundColor == .clear
作为字符串。当它不是。这是一个JSONObject。
另请注意,您没有使用正确的构造函数。
这是你应该做的事情:
time
答案 1 :(得分:1)
“时间”是另一个JSONObject的关键。 如果您想从“时间”对象中检索美元汇率,请尝试:
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);
更多信息:http://www.oracle.com/technetwork/articles/java/json-1973242.html 您可以在https://jsonformatter.curiousconcept.com/轻松检查JSON结构 希望我能帮助你!