Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I am currently new in Json and faced to a problem. I Searched a lot but could not find an answer to it!

I am getting a list of names from a json url. 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". 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.

I tried to print arr.length() in each iteration and I get 1!! but I do not really know why i do receive this error?!

Thanks in advance

share|improve this question
    
Can you post the JSON which is causing this too? –  Adam Mar 7 at 22:14
    
Yes I can post the json. In fact I want to clean my json file by removing duplicated names. I can send my unclean json and it works well, only when i check it with this for : for (int a = 0; a <= arr.length(); a++) { problem apear! –  Peyman Toreini Mar 7 at 22:17
    
you can see the json here : lanzarote.informatik.rwth-aachen.de/palm/Api/exportprofile/… –  Peyman Toreini Mar 7 at 22:20

1 Answer 1

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

for(int i=0; i < Array.lenth(); i++)
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.