Technology Blogs by Members
Explore a vibrant mix of technical expertise, industry insights, and tech buzz in member blogs covering SAP products, technology, and events. Get in the mix!
Showing results for 
Search instead for 
Did you mean: 
Active Participant
Hey guys,

After a long time without writing here I decided to take a few minutes to share some code that I recently used in a project and that I couldn't find here in the community.

Basically, the code I'm going to share has a simple and highly requested functionality in some projects, cleaning JSON messages, removing null and blank fields (Ex. "field" : "" or "field" : null.).

import groovy.json.JsonBuilder
import groovy.json.JsonSlurper

def Message processData(Message message) {
def body = message.getBody(String.class)
def jsonSlurper = new JsonSlurper()
def jsonObject = jsonSlurper.parseText(body)
def cleanedObject = removeEmptyFields(jsonObject)
def jsonBuilder = new JsonBuilder(cleanedObject)
return message

def removeEmptyFields(def object) {
if (object instanceof Map) {
object.entrySet().removeAll { it.value == null || (it.value instanceof String && it.value.trim() == "") }
object.collectEntries { [it.key, removeEmptyFields(it.value)] }
} else if (object instanceof List) {
object.collect { removeEmptyFields(it) }.findAll { it != null }
} else {


Now let's test it, which is very simple as below:


That's it guys, glad I helped you and comment if you're using the code in your projects.











Labels in this area