This blog covers a groovy script for converting deep nested JSON elements from string to double or boolean data types.
In some cases some requirements may arise wherein some specific fields of a JSON are not accepted in string format by the target system and only double or numeric values are accepted. The below groovy covers such requirements.
While converting XML to JSON format, all characters are converted to default String type (even though the XSD definition may say it’s of int/boolean data type). To convert string to numeric or boolean data types, a groovy script can be used to achieve the same.
//Groovy : Convert deep nested specified JSON elements to double or Boolean data types
import groovy.json.JsonSlurper
import groovy.json.JsonOutput
import groovy.json.JsonBuilder
import com.sap.gateway.ip.core.customdev.util.Message
def Message processData(Message message)
{
def body = message.getBody(java.lang.String)
def jsonSlurper = new JsonSlurper()
def json = new JsonSlurper().parseText(body)
//Get Message Properties
def NumericFieldsToConvert=message.getProperty("Numericfields").split(",")
def BooleanFieldsToConvert=message.getProperty("Booleanfields").split(",")
// Call the conversion function with the root of the JSON
convertGPaths(json,NumericFieldsToConvert,BooleanFieldsToConvert)
// Convert the modified JSON back to a string
def modifiedJsonStr = new JsonBuilder(json).toPrettyString()
message.setBody(modifiedJsonStr)
return message
}
def convertGPaths(node,NumericFieldsToConvert,BooleanFieldsToConvert)
{
if (node instanceof Map)
{
println("Node:"+node)
node.each { key, value ->
println("Key : "+key)
println("Value :"+value)
//Double fields
if (key in NumericFieldsToConvert)
{
try
{
node[key] = value.toDouble()
}//try
catch (Exception e)
{
node[key] = value
}//catch
} //if
//boolean fields
else if (key in BooleanFieldsToConvert)
{
try
{
node[key] = value.toBoolean()
}//try
catch (Exception e)
{
node[key] = value
}//catch
} //if
else if (value instanceof Map || value instanceof List)
{
node[key]=convertGPaths(value,NumericFieldsToConvert,BooleanFieldsToConvert)
}//else if
else
{
node[key] = value
}
}//node.each
}//if
else if (node instanceof List)
{
node.each { item ->
if (item instanceof Map || item instanceof List)
{
convertGPaths(item,NumericFieldsToConvert,BooleanFieldsToConvert)
}//if
}//node.each
}//else if
}//convertGPaths
Simulation Results for String to Boolean, Double type conversion
NOTE : Pass comma separated values of Boolean and Numeric fields to be converted through a content modifier. In case of additional additions to fields, this can be directly configured, thus making it more dynamic.
Groovy script to convert specific elements of JSON from default String to Boolean/Numeric data was illustrated above.
Comments or feedback/suggestions, pros/cons with respect to the above are welcome from fellow Integration folks.