【问题标题】:How reach json values in depth of other levels?如何深入到其他级别达到 json 值?
【发布时间】:2015-07-28 12:43:56
【问题描述】:

假设我有这个 JSON 文件:

{
    "level1" :{
        "type": "x"
    },
    "level2" :{
        "level3": {
            "level3": {
                "type" : "Y"
            }
        }
    }
}

使用Jackson,如何获取type = Y值?

也可以通过gson.jar到达

到目前为止我尝试的是:

ObjectMapper ob = new ObjectMapper();
String jsonContent = "...";
JsonNode root = ob.readTree(jsonContent)
root.path("level1");                      //return results fine
root.path("level2").path("level3");       //not return any results
root.path("level2/level3");               //not return any results

【问题讨论】:

  • 强制性问题:what have you tried 以及它为什么不适合您?
  • 更新了,请看添加的代码
  • 您应该将 key:value 对与 , 分开。
  • 请给我一个例子
  • 检查my answer(您可能需要刷新此页面)。

标签: java json jackson gson


【解决方案1】:

您的 JSON 无效,因为您没有用逗号分隔 key:value,,如 http://json.org 所示

所以把你的 JSON 改成

{
    "level1" :{
        "type": "x"
    }, <-- add this comma
    "level2" :{
        "level3": {
            "level3": {
                "type" : "Y"
            }
        }
    }
}

现在你应该可以使用了

JsonNode root = new ObjectMapper().readTree(jsonContent);
root.path("level2")
      .path("level3")
        .path("level3");

使用 Gson 你的代码看起来像

JsonObject root = new JsonParser().parse(jsonContent).getAsJsonObject();
root.getAsJsonObject("level2")
      .getAsJsonObject("level3")
        .getAsJsonObject("level3");

【讨论】:

  • 虽然我修复了我的 JSON,但我的代码中有这个逗号,但感谢您的回答。
  • @gamil 我怀疑您的真实 JSON 是有效的,因为您没有在 ob.readTree(jsonContent) 中提及任何解析异常,但为了清楚起见,我添加了有关逗号的信息,因为您的 JSON 示例无效。无论如何,您是否设法使用此答案中的代码解决了您的问题?
【解决方案2】:

除了使用path 遍历树(确实有效)之外,您还可以考虑使用方法at 直接支持的JSON 路径。 比如:

String type = root.at("/level2/level3/level3/type").asText();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多