gpt4 book ai didi

java - Jackson Json遍历封装树

转载 作者:行者123 更新时间:2023-12-01 09:38:36 27 4
gpt4 key购买 nike

我有一个像这样的架构(简化):

{
"range": {
"offset": 0,
"limit": 1,
"total": 2
},
"items": [
{
"id": 11,
"name": "foo",
"children": [
{
"id": 112,
"name": "bar",
"children": [
{
"id": 113,
"name": "foobar",
"type": "file"
}
],
"type": "folder"
},
{
"id": 212,
"name": "foofoo",
"type": "file"
}
],
"type": "room"
},
{
"id": 21,
"name": "barbar",
"type": "room"
}
]
}

我只需要读取第一个房间(项目)中的“id”等特定值。为此,我需要使用文件夹或文件类型迭代每个级别上的所有项目(n 个根项目,n 个子项目)。

现在我有这个代码:

POJO

public static class Item {
public int id;
}

jackson 树迭代

ObjectMapper mapper = new ObjectMapper();
com.fasterxml.jackson.databind.JsonNode root = mapper.readTree(JSON);
root = root.get("items").get(0);
TypeReference<List<Item>> typeRef = new TypeReference<List<Item>>(){};
List<Item> list = mapper.readValue(root.traverse(), typeRef);
for (Item f : list) {
System.out.println(f.id);
}

如何获取特定类型的所有项目中所有子项的所有 id?如何在不定义整个架构的情况下避免“无法识别的字段”异常?

非常感谢您的帮助!

最佳答案

尝试使用 java8 函数,它可以用更少的行完成很多工作,

ObjectMapper mapper = new ObjectMapper();
Pass your json value
Map obj = mapper.readValue(s, Map.class);

List<Object> items= (List<Object>) obj.get("items");
Object[] Ids= items
.stream()
.filter(items-> ((Map)items).get("type").equals("room"))
.toArray()

关于java - Jackson Json遍历封装树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38624837/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com