【发布时间】:2017-12-14 13:09:35
【问题描述】:
我正在尝试在以下链接中获取键“GBP”的值:https://api.fixer.io/latest
我已成功连接到 API,并且能够循环访问密钥,直到获得“费率”。不过,在找到“英镑”之前,我不知道如何在所有货币中循环。
注意:我正在解析 Json - 我正在努力解析其中包含 Json 的 Json 对象。它与您引用的重复项不同。
到目前为止,我的代码如下所示:
String urlStr = "https://api.fixer.io/latest";
AsyncTask.execute(new Runnable() {
@Override
public void run() {
// Create URL
URL url = null;
try {
url = new URL(urlStr);
} catch (MalformedURLException e) {
e.printStackTrace();
}
// Create connection
try {
HttpURLConnection myConnection =
(HttpURLConnection) url.openConnection();
if (myConnection.getResponseCode() == 200) {
InputStream responseBody = myConnection.getInputStream();
InputStreamReader responseBodyReader =
new InputStreamReader(responseBody, "UTF-8");
JsonReader jsonReader = new JsonReader(responseBodyReader);
jsonReader.beginObject(); // Start processing the JSON object
while (jsonReader.hasNext()) { // Loop through all keys
String key = jsonReader.nextName(); // Fetch the next key
if (key.equals("rates")) { // Check if desired key
// Fetch the value as a String
String value = jsonReader.nextString();
//currentCurrency = value;
break; // Break out of the loop
} else {
jsonReader.skipValue(); // Skip values of other keys
}
}
} else {
// Error handling code goes here
}
} catch (IOException e) {
e.printStackTrace();
}
}
});
【问题讨论】:
-
@JamLis 请检查我的回答。