我是Android开发的新手,我正在尝试创建一个用于货币转换的Android应用程序。我需要阅读JSON URL才能获得费率。我获得了AMOUNT,CURRENCYFROM和CURRENCYTO的用户输入。我正在尝试阅读的网址如下:http://rate-exchange.appspot.com/currency?from=USD&to=EUR&q=1
读取网址后,我想将值分配给变量。具体来说,我正在尝试获取费率并乘以AMOUNT的用户输入。
我想获取字典(我认为JSON文件具有字典)值和键并将其转换为数据类型变量,如int或string。任何帮助,将不胜感激。感谢
答案 0 :(得分:1)
您可以使用此代码:
public API_Rate_Model getRate() {
API_Rate_Model result = new API_Rate_Model();
try {
HttpResponse response;
HttpClient myClient = new DefaultHttpClient();
HttpPost myConnection = new HttpPost("http://rate-exchange.appspot.com/currency?from=USD&to=EUR&q=1");
try {
response = myClient.execute(myConnection);
String JSONString = EntityUtils.toString(response.getEntity(),
"UTF-8");
Log.i(BaseID.TAG, JSONString);
JSONObject json = null;
json = new JSONObject(JSONString);
result.setTo(json.getString("to"));
result.setRate(json.getDouble("rate"));
result.setFrom(json.getString("from"));
result.setValue(json.getDouble("v"));
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
API_Rate_Model类:
public class API_Rate_Model {
private String to;
private Double rate;
private String from;
private Double value;
public API_001_Model() {
to = "";
rate = 0.0;
from = "";
value = 0.0;
}
public Double getRate() {
return rate;
}
public void setRate(Double rate) {
this.rate = rate;
}
public int getValue() {
return value;
}
public void setValue(Double value) {
this.value = value;
}
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public String getTo() {
return to;
}
public void setTo(String to) {
this.to= to;
}
}
此代码将向服务器发送一个帖子,然后将响应转换为字符串,然后处理JSON字符串响应。我希望我的回答可以帮到你,但如果你有任何问题可以随意在评论中提问:)