jsongroovynulljsonbuilder

Exclude null values using JSONBuilder in Groovy


Is it possible to create JSON values in Groovy using the default JsonBuilder library to exclude all the null values of an object? Such as what Jackson does in Java by annotating classes to exclude null values.

An example would be:

{
   "userId": "25",
   "givenName": "John",
   "familyName": null,
   "created": 1360080426303
}

Which should be printed as:

{
   "userId": "25",
   "givenName": "John",
   "created": 1360080426303
}

Solution

  • Not sure if it's OK for you as my method works on a Map with List properties:

    def map = [a:"a",b:"b",c:null,d:["a1","b1","c1",null,[d1:"d1",d2:null]]]
    
    def denull(obj) {
      if(obj instanceof Map) {
        obj.collectEntries {k, v ->
          if(v) [(k): denull(v)] else [:]
        }
      } else if(obj instanceof List) {
        obj.collect { denull(it) }.findAll { it != null }
      } else {
        obj
      }
    }
    
    println map
    println denull(map)
    

    yields:

    [a:a, b:b, c:null, d:[a1, b1, c1, null, [d1:d1, d2:null]]]
    [a:a, b:b, d:[a1, b1, c1, [d1:d1]]]
    

    After filter null values out, you then can render the Map as JSON.