Search code examples
javajsondeserializationjson-simple

Java json-simple accessing via object properties


One of my gripes with JSON-Simple is that if you have a heavily nested structure, then it becomes very verbose to access information.

Consider a trivial JSON object:

{
  "announcements": {
    "inGame": {
      "playerDied": "{arg1} has died"
    }
  }
}

Should I want to print out "{arg1} has died", as I currently understand it, I must do the following:

 InputStreamReader inputStreamReader =
         new InputStreamReader(getClass().getResourceAsStream(configurationPath));

 JSONObject jsonObject = (JSONObject) parser.parse(inputStreamReader);

 String died = (String)((JSONObject)((JSONObject)jsonObject.get("announcements")).get("inGame")).get("playerDied");

 System.out.println(died);

As you can see, lots of casting, and lots of chaining.

My question is: Is there an easier way to go about this?

For example:

String died = jsonObject.get("announcements").get("inGame").get("playerDied");

Or, even better:

String died = jsonObject.get("announcements.inGame.playerDied");

I feel like I'm missing something.


Solution

  • You are looking for jsonpath for jsons on the lines of xpath for xmls. Check this:

    https://github.com/jayway/JsonPath

    I have used this and it works like a charm.