javajsonparsingsimplejson

JSON.simple - How to correctly access nested JSON objects


Example of my json file is

{
  "collection": [
    {
      "trophy-name": {
        "text": "swimming",
        "text2": "fast swimming"
      },
      "length": "50m",
      "pool": "outside",
      "weather": "20"
    }
  ]
}

Right now I am able to get values from lenght, pool and weather. But I am stuck on how to access the nested array nested object trophy-name.

My code is:

public class main {
    
    public static void main(String[] args) throws FileNotFoundException, IOException, ParseException
    {         

        JSONParser parser = new JSONParser();
        Object obj = parser.parse(new FileReader("..."));   // json path
        JSONObject jsonObject = (JSONObject) obj;           
        JSONArray array = (JSONArray) jsonObject.get("collection"); 
 
        for (Object number : array ) 
        {
            JSONObject testObj = (JSONObject) number;   

            String pool = (String)testObj.get("pool");

            System.out.println(testObj.get("length"));
            System.out.println(pool);
            System.out.println(testObj.get("weather"));         
        }           
    }   
}

This is my first time experimenting with json files so I am trying to play around with it so the code is not great.

I probably have to create new object like

JSONObject trophyObj = (JSONObject) jsonObject.get("trophy-name");

And then from there I should be able to get the text with this?

String troph = (String) trophyObj.get("text");

Even if I that is correct I am not sure how to implement it into the loop or if there is better way to do the loop? Dont mind redoing the code differently and any advice appreciated.


Solution

  • Yes, you are right, simply extract the JSONObject within the loop and then get the required fields.

    public class main {
    
        public static void main(String[] args) throws FileNotFoundException, IOException, ParseException
        {
    
            JSONParser parser = new JSONParser();
            Object obj = parser.parse(new FileReader("..."));   // json path
            JSONObject jsonObject = (JSONObject) obj;
            JSONArray array = (JSONArray) jsonObject.get("collection");
    
            for (Object number : array )
            {
                JSONObject testObj = (JSONObject) number;
    
                String pool = (String)testObj.get("pool");
                System.out.println(testObj.get("length"));
                System.out.println(pool);
                System.out.println(testObj.get("weather"));
    
                JSONObject trophyObj = (JSONObject) testObj.get("trophy-name");
                System.out.println((String)trophyObj.get("text"));
                System.out.println((String)trophyObj.get("text2"));
            }
        }
    }