当使用Jackson值的根节点只有一个值时,如何读取? [英] How to read the root nodes when they only have a value using Jackson?

查看:293
本文介绍了当使用Jackson值的根节点只有一个值时,如何读取?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下方法读取了一个有效的JSON文件,该文件的格式如下所示(我无法控制),其中只有根节点的值:

I read in a valid JSON file, which has the format shown below (I have no control in that) with only values for the root nodes, using:

import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;
JsonNode rootNode = jsonMapper.readTree(belowString);

  1. 如何获取我不知道的根节点名称(下面是第一个和第二个)?
  2. 随后,我还需要读取出席值

{
"First": [{

        "name": "Bill",
        "groupName": "team1",
        "groupType": "golf",
        "info": [{
            "name": "George",
            "groupName": "Caddy"
        }],
        "attending": false
    },
    {
        "name": "Fred",
        "groupName": "team2",
        "groupType": "golf",
        "info": [{
            "name": "Todd",
            "groupName": "caddy"
        }],
        "attending": false
    },
    {
        "name": "Mike",
        "groupName": "team3",
        "groupType": "golf",
        "info": [{
            "name": "Peter",
            "groupName": "caddy"
        }],
        "attending": false
    }
],
"Second": [{

    "name": "Alan",
    "groupName": "team4",
    "groupType": "golf",
    "info": [{
        "name": "Tony",
        "groupName": "caddy"
    }],
    "attending": false
}]
}

已接受的答案解决了#1. 这是我用于#2访问嵌套节点的分辨率:

The accepted answer solved #1. This is the resolution I used for #2 to access the nested nodes:

while (iter.hasNext()) {
   Map.Entry<String, JsonNode> entry = iter.next();

   System.out.println("key: " + entry.getKey());
   System.out.println("value: " + entry.getValue());

   if (entry.getValue().isArray()) {
       JsonNode attending = entry.getValue().get(1).get("attending");
       System.out.println("attending = " + attending.toString());
   }
}

推荐答案

获取字段名称:

Iterator<String> iter = rootNode.fieldNames();
while (iter.hasNext()) {
    System.out.println("field: " + iter.next());
}

要获取名称和值:

Iterator<Entry<String, JsonNode>> iter = rootNode.fields();
while (iter.hasNext()) {
    Entry<String, JsonNode> entry = iter.next();
    System.out.println("key: " + entry.getKey());
    System.out.println("value: " + entry.getValue());
}

这篇关于当使用Jackson值的根节点只有一个值时,如何读取?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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