从表中访问数据 - JSON / Java

时间:2016-11-02 14:08:52

标签: java json parsing

我需要访问“mid”但我需要以某种方式对其进行排序,因此我需要获取“代码”然后获得“mid”值。

你能帮助我吗,我不知道如何参考。

这就是我所拥有的:

public void onSuccess(String response) {

    Log.i("CHACHING", "HTTP Sucess");

    try {
        JSONObject jsonObj = new JSONObject(response);
        JSONObject ratesObject = jonObj.getJSONObject("rates");

        String gbpcode = ratesObject.getString("code");
        Double gbpRate = ratesObject.getDouble(gbpcode."mid");
        Log.i("CHACHING", "GBP: " + gbpRate);
        //  Log.i("CHACHING", "EUR: " + eurRate);

        Double usds = Double.valueOf(usdValue.getText().toString());
        Double gbps = usds * gbpRate;
        // Double euros = usds * eurRate;
        gbpValue.setText("GBP: " + String.valueOf(gbps));

    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

,json看起来像这样

http://api.nbp.pl/api/exchangerates/tables/A/?format=json

1 个答案:

答案 0 :(得分:0)

收到的json是json对象列表(json数组),在每个json对象中,“rates”是另一个json数组。

所以,为了访问mid。

public void onSuccess(String response) { Log.i("CHACHING", "HTTP Sucess");

        try {
    JSONArray jsonArr = new JSONArray(response);
    JSONObject jsonObj=jsonArr.getJSONObject(0);
    //this jsonObj holds the first jsonObject of your response

    JSONArray rateList = jonObj.getJSONArray("rates");
    //rateList has the list of rates you obtained

    //NOW, to get all mids for this rate list

    for(int i=0;i<rateList.length();i++) {
         JSONObject jO=rateList.getJSONObject(i);
         Double mid=jO.getDouble("mid");
         Double gbpcode = jO.getString("code");
    /*
    your code here
    */
    }   
} catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
}