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!
cancel
Showing results for 
Search instead for 
Did you mean: 
arrezende
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 com.sap.gateway.ip.core.customdev.util.Message
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)
message.setBody(jsonBuilder.toPrettyString())
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 {
object
}
}

 

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.

 

Bye!

 

 

 

 

 

 

 

 

 
2 Comments
Labels in this area