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

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

问题描述

如何使用Jackson从JSON树接收节点名称?
JSON-File看起来像这样:

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 #theerator()
不包含密钥,需要迭代以不同方式

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天全站免登陆