groovyjsonslurper

Groovy JsonSlurper - How to check for null value vs missing field?


I am parsing a JSON string with Groovy's JsonSlurper. I want to find out how to (1) check if a field is missing from the string OR (2) if its value is set to null. This is my code:

def JsonSlurper jSlurp = new JsonSlurper()
def obj = jSlurp.parseText(myJsonString)
assert obj.myField == null

Unfortunately, this does not tell me if the field is missing or if its present with a value of null. How do I figure that out?


Solution

  • def obj = new groovy.json.JsonSlurper().parseText('{"a":null, "b":1}')
    assert obj.containsKey('a')==true
    assert obj.a==null
    
    assert obj.containsKey('c')==false
    assert obj.c==null