Jackson JSON:从 json-tree 获取节点名称 [英] Jackson JSON: get node name from json-tree

查看:20
本文介绍了Jackson JSON:从 json-tree 获取节点名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 Jackson 从 JSON 树接收节点名称?JSON 文件如下所示:

How can I receive the node names from a JSON tree using Jackson? The JSON-File looks something like this:

{  
    node1:"value1",
    node2:"value2",
    node3:{  
        node3.1:"value3.1",
        node3.2:"value3.2"
    }
}

我有

JsonNode rootNode = mapper.readTree(fileReader);

并且需要像

for (JsonNode node : rootNode){
    if (node.getName().equals("foo"){
        //bar
  }
}

谢谢.

推荐答案

此答案适用于 2+ 之前的 Jackson 版本(最初为 1.8 编写).请参阅@SupunSameera 的回答,了解适用于较新版本 Jackson 的版本.

This answer applies to Jackson versions prior to 2+ (originally written for 1.8). See @SupunSameera's answer for a version that works with newer versions of Jackson.

节点名称"的 JSON 术语是键".由于 JsonNode#iterator()不包括键,你需要迭代 不同:

The JSON terms for "node name" is "key." Since JsonNode#iterator() does not include keys, you need to iterate differently:

for (Map.Entry<String, JsonNode> elt : rootNode.fields())
{
    if ("foo".equals(elt.getKey()))
    {
        // bar
    }
}

如果您需要查看密钥,您可以使用 JsonNode#fieldNames():

If you only need to see the keys, you can simplify things a bit with JsonNode#fieldNames():

for (String key : rootNode.fieldNames())
{
    if ("foo".equals(key))
    {
        // bar
    }
}

<小时>

如果你只想找到键为 "foo" 的节点,你可以 直接访问.与使用循环相比,这将产生更好的性能(恒定时间查找)和更清晰/更清晰的代码:


And if you just want to find the node with key "foo", you can access it directly. This will yield better performance (constant-time lookup) and cleaner/clearer code than using a loop:

JsonNode foo = rootNode.get("foo");
if (foo != null)
{
    // frob that widget
}

这篇关于Jackson JSON:从 json-tree 获取节点名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆