javajsonmavenorg.json

How can I find the value of an unnamed JSON object? (org.json) (java)


[Java 17 using the org.json parsing library. Not able to switch to Gson because I've written an insane amount of code in org.json :/ ]

Hello! I am using an API in Java with the org.json JSON parsing library. I need to get the value of an unnamed JSON object in an array.

{
  "lorem": [
   { // this object needs to be retrieved
     "ipsum":"dolor",
     "sit":"amet",
     "consectetur":"adipiscing"
   },
   { // this object also needs to be retrieved
     "ipsum":"dolor",
     "sit":"amet",
     "consectetur":"adipiscing"
   },
   { // this object needs to be retrieved
     "ipsum":"dolor",
     "sit":"amet",
     "consectetur":"adipiscing"
   }
  ]
}

Note that the entire JSON file is NOT an array, there is just one JSON array inside of a JSON object. How would I be able to get the value of all of these unnamed fields inside of the array?

Thanks in advance for any help, and also sorry if this question has been asked before, I wasn't able to find anything on it when I searched for it on Stackoverflow.


Solution

  • Those objects aren't really unnamed objects, they are part of an JSON array. Because they are contained in an array, we can iterate through that array and we can retrieve every object by index.

    Assuming that the we read the json provided above from a file:

    public static void main(String[] args) throws FileNotFoundException {
        String resourceName = "src/main/resources/input.json";
        InputStream inputStream = new FileInputStream(resourceName);
    
        JSONTokener jsonTokener = new JSONTokener(inputStream);
        JSONObject jsonObject = new JSONObject(jsonTokener);
    
        // Get the array named lorem from the main object
        JSONArray jsonArray = jsonObject.getJSONArray("lorem");
    
        // Iterate through the array and get every element by index
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject object = jsonArray.getJSONObject(i);
            System.out.println("ipsum:" + object.get("ipsum"));
            System.out.println("sit:" + object.get("sit"));
            System.out.println("consectetur:" + object.get("consectetur"));
        }
    }
    

    Also, JSONObject has a toList method, which returns a List<Object>.