cancel
Showing results for 
Search instead for 
Did you mean: 

SAP Cloud Integration Groovy script to convert JSON string to integer

beverely_parks2
Participant
0 Kudos

I have a requirement to send a JSON file to a trading partner. As a part of this requirement, there is one field that needs to be converted from a string to an integer. I have that working when the field is populated, but most of the time, this field will not be populated so it will not exist in the JSON file. I have tried to follow this blog: http://saphcidemo.blogspot.com/2017/10/json-code-for-conversion-of-string-to.html . The issue that I'm currently having is that when I add the if(jsonDataObject.assignedTo!= null) statement to my script, I'm receiving the error: java.lang.NullPointerException: while trying to invoke the method com.sap.gateway.ip.core.customdev.util.Message.getBody() of a null object loaded from local variable 'result'

This is the script that I'm working with:

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

import groovy.json.*

def Message processData(Message message)

{

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

def jsonSlurper = new JsonSlurper();

def jsonDataObject = jsonSlurper.parseText(jsonbody);

//Convert the JSON String to Int

//if (jsonDataObject.check_transaction_code!= null){

jsonDataObject.check_transaction_code = convertToInt(jsonDataObject.check_transaction_code);

//Integer conversion

message.setBody(new JsonBuilder(jsonDataObject).toString());

return message;

//}

}

static Object convertToInt(Object inputValue){

if(inputValue.isNumber()){

return inputValue.toInteger();

}else{

return inputValue;

}

}

Would anyone be able to advise me where I'm going wrong?

View Entire Topic
Sriprasadsbhat
Active Contributor
0 Kudos

Hello Beverly,

Please find the below thread which might resolve your issue.

https://answers.sap.com/questions/168650/sap-hci-xml-to-json-converter-string-to-integer.html

Regards,

Sriprasad Shivaram Bhat

beverely_parks2
Participant
0 Kudos

I'm not sure that it does. My issue is that if the field isn't contained in the JSON stream, I'm receiving an exception. I've tried mulitple combinations of if statements, but I can't seem to find the correct one for determining if the field is exists.