如何获得json数组的最大值

时间:2016-02-12 08:48:24

标签: java android json

我遇到了这个错误org.json.JSONException: Index 5 out of range [0..5),我知道它是什么意思JSONArray Exception : Index 50 out of range (0..50)

我的错误在这段代码中,我想在json对象中获取最后一个id怎么做?

        JSONObject maxj  = peoples.getJSONObject(peoples.length());

更多explenation这是以下代码:

 JSONObject jsonObj = new JSONObject(myJSON);
            peoples = jsonObj.getJSONArray("result");
            System.out.println(peoples.length());

            JSONObject maxj  = peoples.getJSONObject(peoples.length());//here is the error because 
            String j_id=  maxj.getString("id");// and here

            Listitem = new ArrayList<Listitem>();
            for(int i=0;i<peoples.length();i++){
                JSONObject c = peoples.getJSONObject(i);
              //  String id ="2";
                String id=  c.getString("id");
                String url = c.getString("url");

在此代码中进入循环并获取id(1,2,3,4)

                String id=  c.getString("id");

我想要的只是the max的最后一个4,那该怎么做呢?

2 个答案:

答案 0 :(得分:2)

length()是4,因为有4个项目。但索引从0开始,因此最后一项将位于索引length() - 1。因此代码应该是:

peoples.getJSONObject(peoples.length() - 1);

答案 1 :(得分:1)

如文件中所述

  

length()返回此数组中的值的数量。

JsonArray长度为4但索引将从0开始,因此索引的值不会为4。

您需要从总长度减少1,因此peoples.length()-1将是您的解决方案。