【问题标题】:JSONObject has nested keyJSONObject 有嵌套键
【发布时间】:2021-03-01 08:21:15
【问题描述】:

如果存在特定值,我想读取一个 json 配置文件并执行代码。

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

我使用来自 maven Central 的 org.json

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

默认情况下,database.port 不会被识别为嵌套路径。我如何告诉 org.json 这是一个嵌套路径?

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

这工作得很好,但我有更多的嵌套值它变得相当混乱。

有没有更好的方法来获取内容而不是两次写入路径(JSONObject#has(...) 1x 和 JSONObject#getInt(...) 1x)

【问题讨论】:

  • JSONObject d=jsonObject.get("database");字符串端口=d.getString("端口");
  • @rupps 然后我必须使用if (jsonObject.has("database") && jsonObject.getJSONObject("database").has("port")) 这很不方便(特别是如果我有更多的嵌套值)。
  • 你使用的json库是最基础的,不包含嵌套路径的nethods。

标签: java json org.json


【解决方案1】:

正如 rupps 所说,org.json 不支持嵌套路径。我升级到支持更高级解析的 gson。 JsonPath 看起来不错,但对我的要求来说似乎有点矫枉过正。

【讨论】:

    【解决方案2】:

    抱歉,org.json 不支持嵌套解析。但是你可以尝试将JSON转成bean,会容易很多

    【讨论】:

      猜你喜欢
      • 2011-03-09
      • 1970-01-01
      • 2021-05-28
      • 1970-01-01
      • 2019-12-03
      • 1970-01-01
      • 2015-07-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多