-1

I'm currently trying to process some JSON but it's given me an error saying that "Index 0 out of range [0..0)" the affected line is the one that is commented out.

JSONObject parentObject3 = new JSONObject(finalJSON3);
JSONArray parentArray3 = parentObject3.getJSONArray("players");
//JSONObject finalObject3 = parentArray3.getJSONObject(0);

tempGameBans = finalObject3.getInt("NumberOfBans");
tempVacBans = finalObject3.getInt("NumberOfMutes");;

Here is my JSON:

{
    "players": [
        {
            "userID": "5648131",
            "NumberOfBans": 0,
            "NumberOfMutes": 1,
        }
    ]

}

Edit: Currently I am only looking for 1 object per JSON URL so the Index should always be 0, unlike the possible duplicate which seems to be looking for multiple objects.

Edit 2: I found out what the issue is and it's due to the JSON not being correctly sent from my server. Thanks for the help anyway guys.

J_Dadh
  • 23
  • 1
  • 6

3 Answers3

2
    String jsonString = new String("{\"players\": [{\"userID\": \"5648131\",\"NumberOfBans\": 0,\"NumberOfMutes\": 1}]}");
    JSONObject parentObject3 = new JSONObject(jsonString);
    JSONArray parentArray3 = parentObject3.getJSONArray("players");
    JSONObject finalObject3 = parentArray3.getJSONObject(0);

    System.out.println(finalObject3.getInt("userID"));
    System.out.println(finalObject3.getInt("NumberOfBans"));
    System.out.println(finalObject3.getInt("NumberOfMutes"));

This is working fine, so there has to be some another issue.

Adinia
  • 3,722
  • 5
  • 40
  • 58
B. Patel
  • 69
  • 3
1

You are calling some attribute either not in the JsonObject or the attribute value at that specified index doesn't exist.

Naveen Tamrakar
  • 3,349
  • 1
  • 19
  • 28
Amal lal T L
  • 400
  • 5
  • 20
  • Every value I am calling is in the JSON Object, so I'm not sure why it's giving me an error. – J_Dadh Aug 16 '17 at 10:15
  • `JSONObject object = new JSONObject();` `object.get(1)` instead of getInt(); Please try this.I also some times get this error.It may be reason of value not being assigned!Please post your final JSON – Amal lal T L Aug 16 '17 at 10:23
1

Try remove the "," at the end of "NumberOfMutes": 1,.

Qian Sijianhao
  • 564
  • 7
  • 19