1

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.

topcan5
  • 1,511
  • 8
  • 30
  • 54
  • Selections and traversal of this kind are pretty simple when using JsonPath expressions. Have a look into [Jayway JsonPath](https://github.com/json-path/JsonPath) lib or equivalents. – Antot Oct 05 '18 at 06:08

1 Answers1

3

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.

S.K.
  • 3,597
  • 2
  • 16
  • 31