Home > Blockchain >  Accessing Nested Elements of JSON in Java
Accessing Nested Elements of JSON in Java

Time:01-10

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.

CodePudding user response:

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());
}

CodePudding user response:

It looks like you are trying to create a JSONArray object using JSON.getJSONArray("data"), but getJSONArray expects a string as an argument, and you are passing it an actual JSONArray object.

To access the data array, you can simply do:

JSONArray data = JSON.getJSONArray("data");

Then, you can iterate through the data array using a for loop, like you are doing. However, there is an error in your loop's condition: you are using i instead of z. It should be:

for(int z = 1; z<data.length(); z  )

Finally, to access each player profile, you can do:

JSONObject ply = data.getJSONObject(z);

I hope this helps! Let me know if you have any more questions.

CodePudding user response:

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);
    }
  • Related