cancel
Showing results for 
Search instead for 
Did you mean: 

XML to JSON conversion issue in sap cpi

0 Kudos

Hi Experts,

When converting xml to json the standard conveter treats Integer as String. i have referred the note 2521044 - CPI: XML to JSON Converter treats Integer as String and the enclosed groovyscript.

import com.sap.gateway.ip.core.customdev.util.Message;
def Message processData(Message message) {
def body = message.getBody(java.lang.String) as String;

String output = body.replaceAll("\"(\\d+)\"", "\$1");
message.setBody(output);

return message;
}

input payload

{
	"top": "3",
	"objects": [
		{
			"features": [
				{
					"name": "Language",
					"value": "EN"
				},
				{
					"name": "SuppID",
					"value": "000001"
				},
				{
					"name": "Quantity",
					"value": "1.0"
				},
				{
					"name": "Code",
					"value": "00001"
				},
				{
					"name": "ID",
					"value": "0001"
				},
				{
					"name": "Shortext",
					"value": "TestPO"
				}
			]
		}
	]
}

As per my requirement i should only convert the one particular field from string to integer i.e "top": "3", should be replaced to "top": 3, so i tried to acheive this with the below script, but the script is not working as expected.

import com.sap.gateway.ip.core.customdev.util.Message;
import java.util.HashMap;
import groovy.json.*
def Message processData(Message message) {
    
    //Body 
    def body = message.getBody(String.class);
    
    def jsonSlurper = new JsonSlurper()
    def list = jsonSlurper.parseText(body)
    
     list.Root.each{
        it.top=Integer.parseInt(it.get("top").toString().replace(" ",""));        
        }

    def jsonOP = JsonOutput.toJson(list)

    message.setBody(jsonOP)
    return message;
}

Please help me with your valuable suggestions to achieve the requirement.

Regards

Revathi

View Entire Topic
0 Kudos

Hi revathich,

Could you try below code.

import com.sap.gateway.ip.core.customdev.util.Message;
import java.util.HashMap;
import groovy.json.*

def Message processData(Message message) {

    //Body
    def body = message.getBody(String.class);

    def jsonSlurper = new JsonSlurper()
    def list = jsonSlurper.parseText(body)
    list['top'] = Integer.parseInt(list['top'])
    def jsonOP = JsonOutput.toJson(list)
    message.setBody(jsonOP)
    return message;
 }

hope this helps !

thanks and regards,

Praveen T

0 Kudos

Hi Praveen,

Thank you for sharign the code. It is working as expected.

Regards

Revathi