java - 当根节点只有一个值时,如何使用 Jackson 读取根节点?

标签 java json jackson

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

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 访问嵌套节点的分辨率:

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());
   }
}

最佳答案

如果 readTree(..) 不是必需的,您还可以使用 readValue(..) 将此 Json 反序列化为 Map,像:

@Test
public void test() throws Exception {
    ObjectMapper jsonMapper = new ObjectMapper();
    // JSON contains this kind of a structure
    Map<String, List<Map<String, Object>>> map = jsonMapper
                // test.json should be in the same package as test and contain 
                // your Json
                .readValue(getClass().getResourceAsStream("test.json"), Map.class);
    // Result of this loggion below
    map.entrySet().forEach(entry -> {
        log.info("key: {}", entry.getKey());
        entry.getValue().forEach(person -> {
            log.info(" {} attending: {}", person.get("name"), person.get("attending"));
        });
    });
}

日志应该是这样的:

key: First
Bill attending: false
Fred attending: false
Mike attending: false
key: Second
Alan attending: false

关于java - 当根节点只有一个值时,如何使用 Jackson 读取根节点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54205005/

相关文章:

java - 使用 jackson 将自定义反序列化类添加到已经存在的@JsonDeserialize 注释

java - 在 Webapp 项目中使用 Tomcat 库

java - JOGL - 监控 GPU 内存

android - "Text1/Text2"字符串在android中被替换为"Text1\/Text2"

java - 在 WildFly 上部署 Spring Boot WAR

java - JSON 反序列化属性,包括 $

java - 检测口袋中的设备是否存在

java - 在 Mac OSX Sierra 上安装 Ortus Commandbox,运行 box 会导致错误和异常

php - 在 php 脚本中访问发布的 Json 数据

javascript - 如何过滤 json 并获取在 js 中创建线图的平均值?