我读取了一个有效的 JSON 文件,其格式如下所示(我无法控制),仅包含根节点的值,使用:
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;
JsonNode rootNode = jsonMapper.readTree(belowString);
- 如何获取我不知道的根节点名称(下面的第一个和第二个)?
- 接下来,我还需要读取主值
{
"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/