-1

我对 android 开发相当陌生,我正在尝试创建一个用于货币转换的 android 应用程序。我需要阅读 JSON URL 以获取费率。我得到了 AMOUNT、CURRENCYFROM 和 CURRENCYTO 的用户输入。我要阅读的网址如下:http ://rate-exchange.appspot.com/currency?from=USD&to=EUR&q=1

读取 url 后,我想将值分配给变量。具体来说,我正在尝试获取速率并乘以用户输入的 AMOUNT。

我想获取字典(我认为 JSON 文件有字典)值和键,并将其转换为数据类型变量,例如 int 或 string。任何帮助,将不胜感激。谢谢

4

1 回答 1

1

You can use this code :

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 Class :

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;
    }  
}

this code will sent a post to the server then convert the response to string then process the JSON String response. I hope my answer can helps you, but if you have any question feel free to ask in the comment :)

于 2013-08-20T16:00:05.497 回答