Tuesday 30 July 2024

Nested structure on items to convert from string to integer in JSON

 Nested structure on items to convert from string to integer in JSON: with null value handling

Groovy script:

 

import com.sap.gateway.ip.core.customdev.util.Message;

import groovy.json.*

def Message processData(Message message)

{

def body = message.getBody(java.lang.String) as String;

def jsonSlurper = new JsonSlurper();

def jsonDataObject = jsonSlurper.parseText(body);


//Convert the JSON String to Int

jsonDataObject.SOFulfillmentHeader.SONbr = convertToInt(jsonDataObject.SOFulfillmentHeader.SONbr);

jsonDataObject.SOFulfillmentHeader.ItemDetails.each { item ->

item.Seq = convertToInt(item.Seq)

item.ReqQty = convertToInt(item.ReqQty)

}


//jsonDataObject.assignedTo.account.id = convertToInt(jsonDataObject.assignedTo.account.id);


//Integer conversion  


message.setBody(new JsonBuilder(jsonDataObject).toPrettyString())

return message

}


   def convertToInt(inputValue){

       if(inputValue != null){

        try {  

          return

Integer.parseInt(inputValue.toString())

        }

        catch (NumberFormatException e){

          return inputValue;

        }}

        else{

            return inputValue

        }

   }




No comments:

Post a Comment