逗人。
我能够从Alpha Vantage中检索JSON对象以在我的货币转换器应用程序中使用,但我无法查找我想要的字符串值(即" 5.汇率":&# 34; 17.86300000")因为标识符的空格如下:
{ "实时货币汇率":{ " 1。 From_Currency Code":" USD", " 2。 From_Currency名称":"美元", " 3。 To_Currency Code":" EGP", " 4。 To_Currency名称":"埃及庞德", " 5。汇率":" 17.86300000", " 6。最后更新":" 2017-12-24 14:38:20", " 7。时区":" UTC" }}
以下我的代码捕获字符串值
@Override
protected String doInBackground(String... f_url) {
String urlStr = "https://www.alphavantage.co/query?function=CURRENCY_EXCHANGE_RATE&from_currency="
+ textto.getText()
+ "&to_currency="
+ textfrom.getText()
+ "&apikey=XXXXXXXXX";
String data="";
String converted="";
try {
URL url = new URL(urlStr);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line ="";
while (line != null)
{
line=bufferedReader.readLine();
data = data +line;
}
JSONArray JA = new JSONArray(data);
JSONObject JO = (JSONObject) JA.get(0);
converted = JO.getString("5. Exchange Rate");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return converted;
}
该方法返回空白值,在logcat中没有异常。我已经使用另一个JSON对象测试了代码,标识符中没有空格并且运行良好。
我在这里缺少什么帮助?
答案 0 :(得分:1)
你回复json中没有数组 而是试试这个:
JSONObject reader = new JSONObject(data);
JSONObject sys = reader.getJSONObject("Realtime Currency Exchange Rate");
String currency = sys.getString("5. Exchange Rate");
答案 1 :(得分:1)
尝试使用以下代码
JSONObject JA = new JSONObject(data);
JSONObject JO = (JSONObject) JA.getJSONObject("Realtime Currency Exchange Rate");
converted = JO.getString("5. Exchange Rate");