Exclude null values โ€‹โ€‹with JSONBuilder in Groovy

Is it possible to create JSON values โ€‹โ€‹in Groovy using the default JsonBuilder library to exclude all null values โ€‹โ€‹of the object? For example, what Jackson does in Java, annotating classes to eliminate null values.

Example:

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

What should be printed as:

 { "userId": "25", "givenName": "John", "created": 1360080426303 } 
+4
source share
3 answers

Not sure if this is normal for you, since my method works with 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) 

gives:

 [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 highlighting the null values, you can display the Map as JSON.

+7
source

I used metaClass Groovy to solve this problem, but not sure if it will work in all cases.

I created a class to store the necessary elements, but left optional elements that can have a null (or empty) value.

 private class User { def id def username } 

Then I added data to this class. My use case was rather complicated, so this is a simplified version to show an example of what I did:

 User a = new User(id: 1, username: 'john') User b = new User(id: 2, username: 'bob') def usersList = [a,b] usersList.each { u -> if (u.id == 1) u.metaClass.hobbies = ['fishing','skating'] } def jsonBuilder = new JsonBuilder([users: usersList]) println jsonBuilder.toPrettyString() 

Results:

 { "users": [ { "id": 1, "username": "john", "hobbies": [ "fishing", "skating" ] }, { "id": 2, "username": "bob" } ] } 
+2
source

If you don't need JSONBuilder, you can use com.fasterxml.jackson:

Make Object:

 private static final ObjectMapper JSON_MAPPER = new ObjectMapper().with { setSerializationInclusion(JsonInclude.Include.NON_NULL) setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY) setVisibility(PropertyAccessor.GETTER, JsonAutoDetect.Visibility.NONE) setVisibility(PropertyAccessor.IS_GETTER, JsonAutoDetect.Visibility.NONE) } 

and display a list of such cards (cards can have any object inside):

 println(JSON_MAPPER.writeValueAsString(listOfMaps)) 
0
source

All Articles