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:

Teste

Sara Sampaio

Sara Sampaio

Author Since: March 10, 2022

0 0 votes
Article Rating
Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x