简体   繁体   中英

java - Jackson Json traverse encapsulated tree

I have a schema like this (simplified):

{
  "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"
    }
  ]
}

I need to read only specific values like "id" from the first room (item). For this I need to iterate trough all items on every level (n items for root, n items for n children) with type folder or file.

For now i have this code:

POJO

public static class Item {
  public int id;
}

Jackson Tree Iteration

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

How can i get all id's of all children in all items with specific type? How to avoid the "Unrecognized field" exception without defining the whole schema?

Thank you very much for your help!

Try using java8 functions it has lot to do it in lesser lines ,

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

Use the readTree(...) method to parse the JSON without needing to define the entire schema and find Nodes called "id".

You can then use findValues("id") to get the List of values back.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM