解析JSON并检索Last Element

时间:2015-08-21 23:50:40

标签: java android json

我在下面有以下 JSON 我想在2011-05-01结束时检索最后一个dateTime的值

{
    "activities-log-steps":[
        {"dateTime":"2011-04-27","value":5490},
        {"dateTime":"2011-04-28","value":2344},
        {"dateTime":"2011-04-29","value":2779},
        {"dateTime":"2011-04-30","value":9196},
        {"dateTime":"2011-05-01","value":15828},
        {"dateTime":"2011-05-02","value":1945},
        {"dateTime":"2011-05-03","value":366}
    ]
}

我已经包含了我用来尝试检索该值的当前方法的代码。

 protected void onPostExecute(JSONObject jsonObject) {
            Calendar cal = Calendar.getInstance();
            cal.add(Calendar.DATE, 1);
            SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
            String currentDate = format1.format(cal.getTime());
            if (jsonObject != null) {

                try {

                    name = jsonObject.getString("dateTime" + ":" + "" + currentDate + "," + "value");
                    Toast.makeText(getActivity(), name, Toast.LENGTH_LONG).show();
                    Log.d("Token Access", name);
                    //  _access.setText("Access Token:" + heartrate);
                    new refresh().execute();
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            } else {
                Toast.makeText(getActivity(), "Network Error", Toast.LENGTH_SHORT).show();

            }
        }
    }

这不会返回值

1 个答案:

答案 0 :(得分:1)

JSONArray ar = jsonObject.getJSONArray("activities-log-steps");
JSONObject lastObj = ar.getJSONObject(ar.size()-1);

String dateTime = lastObj.getString("dateTime");
String value = lastObj.getString("value");

您需要找到数组activities-log-steps中的最后一个Object,然后提取您的JSON变量。