Accessing Nested Elements of JSON in Java

50 views Asked by At

I have a java project in which I take a JSON and read its contents. I'm using org.json libraries and I would like to iterate through JSONObjects which are nested in a JSONArray, which is nested in a JSONObject. I keep getting this error though: JSONArray initial value should be a string or collection or array. I'm specifically getting the JSON from a web source, but here is an example of one: http://jsonblob.com/1062033947625799680 I'm particularly concerned about the fact that each player profile is unnamed, but there may be a simple fix for that.

I'd like to get access to each player profile and here is what I have that is causing an error:

import org.json.*;
JSONObject JSON = new JSONObject(content1.toString());
        JSONArray data = new JSONArray(JSON.getJSONArray("data"));
        for(int z = 1; i<data.length(); i++)
        {
          JSONObject ply = new JSONObject(data.getJSONObject(z));
          System.out.println(ply.toString());
        }

I have a feeling I just don't fully understand the terminology of JSON and/or the library that I'm using, but any help is appreciated.

2

There are 2 answers

1
Sakuragi On

Try this instead:

JSONObject JSON = new JSONObject(content1.toString());
JSONArray data = new JSONArray(JSON.getJSONArray("data"));
for(int i = 0; i<data.length(); i++) {
  JSONObject ply = data.getJSONObject(i);
  System.out.println(ply.toString());
}
0
Josh Lukin On

It turns out I just have to access the particular element in one line:

JSONObject JSON = new JSONObject(content1.toString());
    JSONArray data = JSON.getJSONArray("data");
    for(int z = 0; z<data.length(); z++)
    {
      //JSONObject ply = new JSONObject(data.getJSONObject(z));
      String name = data.getJSONObject(z).getString("skaterFullName");
      System.out.println(name);
    }