'Groovy JSON slurper check child element failed

I have this JSON input

{ "field": "AAA", "list": { "item": [ { "field01": "111", "field02": "222" }, { "field01": "333", "field02": "444" } ] }}

I need to do something on this json based on this condition: item count > 0. I'm trying this code.

def myJson = '..' //above json; def jsonParser = new JsonSlurper(); def jsonObject=jsonParser.parseText(myJson); jsonObject.list.item.size()

But when item doesn't exist I get an exception. How can I get a value telling me item exists under list?



Solution 1:[1]

You can use safe navigation operator jsonObject.list.item?.size() it will return null if item does not exist.

Solution 2:[2]

To check, if there is a item:

if (jsonObject.list.item)
{
  // do your things...
}
else
{
  // no item, so what?
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Hitesh A. Bosamiya
Solution 2 Jost Schwider