gpt4 book ai didi

java - 如何获取json数组的最大值

转载 作者:行者123 更新时间:2023-12-01 21:50:09 28 4
gpt4 key购买 nike

我遇到了这个错误 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());

更多解释如下代码:

 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");

我只想要最后一个值最大值,即4,那么该怎么做?

最佳答案

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

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

关于java - 如何获取json数组的最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35358260/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com