Search code examples
javajsonorg.json

JSONObject has nested key


I want to read a json configuration file and execute code if a specific value exists.

{
    "database": {
        "port": 3306
    }
}

I use org.json from maven central.

if (jsonObject.has("database.port")) {
    // Get content of "database.port" and call logic
}

By default, database.port won't get recognized as a nested path. How can i tell org.json that this is a nested path?

if (jsonObject.has("database") && jsonObject.getJSONObject("database").has("port")

This works just fine, but i have more nested values it gets quite messy.

Is there a better way to get the content instead of writing the path two times (1x for JSONObject#has(...) and 1x for JSONObject#getInt(...))


Solution

  • As rupps said, org.json doesn't support nested paths. I upgraded to gson which supports much more advanced parsing. JsonPath looks nice but it seems a bit overkill for my requirements.