Search code examples
javajsonjson-simple

Parsing a JSONObject inside a JSONObject in a single line with json.simple


Lets say I want to parse a JSONObject with JSONObjects inside of it, which I parse from a string. I want to do this in a single line, like I've done with other libraries, but I'm not sure how.

   JSONParser parser = new JSONParser();
   Object obj = parser.parse(test);
   JSONObject first = (JSONObject) obj;
   JSONObject second = (JSONObject) first.get("feed");
   JSONArray third = (JSONArray) second.get("entry");
   JSONObject fourth = (JSONObject) third.get(0);
   JSONObject fifth = (JSONObject) fourth.get("test");

Is there a way for me to get all these JSONObjects in a single line? With another library I'd just do first.getJSONObject("feed").getJSONArray("entry").getJSONObject(0) etc, but I'm not sure how to do it properly with this library.

Thanks.


Solution

  • You can cast within a single line like this:

    (JSONObject) ((JSONObject) YOURJSONOBJECT.get("YOUR_KEY")).get("ANOTHER_KEY");
    

    This can get messy really quick depending on how many layers deep you have to go though