简体   繁体   English

JSONObject 有嵌套键

[英]JSONObject has nested key

I want to read a json configuration file and execute code if a specific value exists.我想读取 json 配置文件并在存在特定值时执行代码。

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

I use org.json from maven central.我使用来自maven中央的 org.json。

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.默认情况下,database.port 不会被识别为嵌套路径。 How can i tell org.json that this is a nested path?我如何告诉 org.json 这是一个嵌套路径?

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(...))有没有更好的方法来获取内容而不是两次写入路径(JSONObject#has(...) 为 1x,JSONObject#getInt(...) 为 1x)

As rupps said, org.json doesn't support nested paths.正如 rupps 所说, org.json 不支持嵌套路径。 I upgraded to gson which supports much more advanced parsing.我升级到支持更高级解析的 gson。 JsonPath looks nice but it seems a bit overkill for my requirements. JsonPath看起来不错,但对于我的要求来说似乎有点矫枉过正。

Sorry, org.json does not support nested parsing.抱歉,org.json 不支持嵌套解析。 But you can try to convert JSON to bean, it will be much easier但是你可以尝试将 JSON 转换为 bean,会容易得多

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM