简体   繁体   English

JsonArray错误:org.json.JSONException:找不到JSONArray [1]

[英]JsonArray error : org.json.JSONException: JSONArray[1] not found

I am currently new in Json and faced to a problem. 我目前是Json的新手,遇到了一个问题。 I Searched a lot but could not find an answer to it! 我搜索了很多,但找不到答案!

I am getting a list of names from a json url. 我从json网址获取名称列表。 names can be duplicated in this json file but i only want to keep one record of them to my new array which i called "arr". 名称可以在此json文件中重复,但我只想将它们的一个记录保留到我称为“ arr”的新数组中。 You can see the code as following: 您可以看到如下代码:

    JSONArray interests = json.getJSONArray("Interests");
    JSONArray arr = new JSONArray();
    int i = 0;
    int p = 0;
    int e = 0;

    for (; i < interests.length(); i++) {

        JSONArray items = interests.getJSONObject(i).getJSONArray("items");
        for (int j = 0; j < items.length(); j++) {
            String string = items.getJSONObject(j).getString("authors");
            String[] parts = string.split(",");
            for (int k = parts.length - 1; k >= 0; k--) {

                for (int a = 0; a <= arr.length(); a++) {

                    if (arr.length() == 0 || !arr.getJSONObject(a).getString("label").equals(parts[k])) {
                        JSONObject obj = new JSONObject();
                        obj.put("id", p++);
                        // obj.put("value", e++);
                        obj.put("label", parts[k]);
                        arr.put(obj);
                    }
                }
            }

        }

    }

    System.out.print(arr);
}

Problem is when i run this code I get the following error : 问题是当我运行此代码时,出现以下错误:

Exception in thread "main" org.json.JSONException: JSONArray[1] not found. 线程“主” org.json.JSONException中的异常:找不到JSONArray [1]。

I tried to print arr.length() in each iteration and I get 1!! 我尝试在每次迭代中打印arr.length(),我得到1! but I do not really know why i do receive this error?! 但我真的不知道为什么会收到此错误?

Thanks in advance 提前致谢

A common fault of index shifting. 索引移位的常见故障。 Following example: 以下示例:

Array[0] = "foo";
Array[1] = "bar";
for(int i=0; i <= Array.length(); i++)
  doSomesing(Array[i]);

Array.length() will return 2, but index rage is 0 to 1, so the correct would be Array.length()将返回2,但索引范围是0到1,因此正确的方法是

for(int i=0; i < Array.lenth(); i++)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM