Filter JsonNode Array in Jackson without Iterating

2.8k Views Asked by At

Json:

{  
   "type":"book",
   "children":[  
      {  
         "key":"123",
         "name":"book1"
      },
      {  
         "key":"456",
         "name":"book2"
         ]
      }
   ]
}

I just want to get the name of the book as string when key = "456".

This is what I have:

JsonNode root = mapper.readTree(investigation.getFilterModel());
JsonNode children = root.path("children");
            if (children.isArray())
            {
                for (final JsonNode objNode : children)
                {
                    if ("456".equalsIgnoreCase(objNode.path("key").textValue()))
                    {
                        String bookName = objNode.path("name").textValue();
                    }
                }
            }

This works for me. I just want to know is there a cleaner way to do it without looping thru the entire children array? As the size of array can be big.

1

There are 1 best solutions below

0
On BEST ANSWER

That kind of query would not be possible with Jackson. You can at most use JsonPointer expression with it when you know the array index where the element is lying:

root.at("/children/1/name");

You can use JsonPath expression $.children[?(@.key==456)].name for your query which is supported in Jayway JsonPath library.