Reputation: 586
In java jsonpath using jayway we can suppress the exception while jsonpath lookup but is there any similar configuration available in groovy for jsonpath lookup.
Like for example:
import groovy.json.*;
def jsonSlurper = new JsonSlurper()
def object = jsonSlurper.parseText('{"test":{"test1":{"test2":{"test3":"1"}}}}')
print(object["test"]["test8"]["test9"]["d"])
So, as expected it will throw null pointer exception so, is there any way where we can configure to suppress exception and return null if it doesn't exist.
Upvotes: 1
Views: 715
Reputation: 20699
In groovy 3 you can apply null-safe operator also on bracketed elements:
print object?["test"]?["test8"]?["test9"]?["d"]
In groovy 2 and below you can use the getAt()
to do safe-indexing:
print object?.getAt("test")?.getAt("test8")?.getAt("test9")?.getAt("d")
Upvotes: 4