cancel
Showing results for 
Search instead for 
Did you mean: 

How to add prefix to the starting of an XML element in HCI when converting from JSON?

RB777
Product and Topic Expert
Product and Topic Expert

Hi Colleagues,

I am trying to convert a JSON request(coming from External System) to XML(C4C) in HCI. I am using groovy script.

My input json is:

{
    "serviceCall": {
    	"id": "4021788",
    	"statusCode": "-2"
		}
}

Expected Output xml in C4C is:

<glob:ServiceRequestReplicateConf xmlns:glob="http://sap.com/xi/SAPGlobal20/Global">
	<MessageHeader>
		<ID>TEST_INB_SER_CORE</ID>
		<CreationDateTime>2006-03-28T12:00:00.1234567Z</CreationDateTime>
		<TestDataIndicator>false</TestDataIndicator>
		<ReconciliationIndicator>true</ReconciliationIndicator>
		<SenderParty>
			<InternalID schemeID="CommunicationSystemID" schemeAgencyID="310">AAAA</InternalID>
		</SenderParty>
		<RecipientParty>
			<InternalID schemeID="CommunicationSystemID" schemeAgencyID="310">ZZZZ</InternalID>
		</RecipientParty>
		<BusinessScope>
			<TypeCode>3</TypeCode>
			<ID>106</ID>
		</BusinessScope>
	</MessageHeader>
	<ServiceRequestReplicationConfirmationMessage>
		<BasicMessageHeader>
			<ID>SRQ_REQ_CONF_BMH</ID>
		</BasicMessageHeader>
		<ServiceRequestInstance actionCode="02">
			<ID>4021788</ID>
			<StatusText>-2</StatusText>
		</ServiceRequestInstance>
	</ServiceRequestReplicationConfirmationMessage>
</glob:ServiceRequestReplicateConf>

Other than two values from json, I have to hard code all the xml structure with attribute, values, namespace & prefix as above.

Hence what i do is

Step 1: I will modify the received json to the above xml format so that in step 2-JSONtoXML converter can directly convert it and get the output

Code:

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

def Message processData(Message message) {
    //Body 
    //def body = message.getBody(java.lang.String) as String;
    String body = message.getBody(String.class);
    
    def messageLog = messageLogFactory.getMessageLog(message);
    if(messageLog != null){
        messageLog.setStringProperty("Logging#1", "Printing Payload As Attachment");
        messageLog.addAttachmentAsString("Incoming JSON from Postman-Coresystem:", body, "text/json");
        
     }
     
    //Parsing incoming json response from core
    def jsonSlurper     = new JsonSlurper();
    def incomingJson    = jsonSlurper.parseText(body) ;
    //Retreive the values from incomingJson
    String serviceCallID = incomingJson.serviceCall.id;
    String statusCode    = incomingJson.serviceCall.statusCode;

    //Set the values to message property
    message.setProperty("id",serviceCallID);
    message.setProperty("statusCode",statusCode);
    
    //Build new json with the c4c request structure
    def builder = new JsonBuilder()
    builder.ServiceRequestReplicateConf {
        MessageHeader {
            ID('MJTEST_CORE_TO_C4C')
            CreationDateTime('2018-07-07T12:00:00.1234567Z')
            TestDataIndicator('false')
            ReconciliationIndicator('true')
            SenderParty {
                InternalID {
                    '@schemeID'('CommunicationSystemID')
                    '@schemeAgencyID'('310')
                    '$title'('AAAA')
                }
            }
            RecipientParty {
                InternalID {
                    '@schemeID'('CommunicationSystemID')
                    '@schemeAgencyID'('310')
                    '$title'('ZZZZ')
                }
            }
            BusinessScope {
                TypeCode('3')
                ID('106')
            }
        }
        ServiceRequestReplicationConfirmationMessage {
            BasicMessageHeader {
               ID('SRQ_REQ_CONF')
            }
            ServiceRequestInstance {
                '@actionCode'('02')
                ID(serviceCallID)
		StatusText(statusCode)
            }
        }
    }
   String newjson = JsonOutput.prettyPrint(builder.toString());
    def messageLog2 = messageLogFactory.getMessageLog(message);
    if(messageLog != null){
        messageLog.setStringProperty("Logging#1", "Printing Payload As Attachment");
        messageLog.addAttachmentAsString("Remodelled Json with complete Structure like C4C:", newjson, "text/json");
    }
    message.setBody(newjson);
    return message;
}
Modified Output Json
{
    "ServiceRequestReplicateConf": {
        "MessageHeader": {
            "ID": "MJTEST_CORE_TO_C4C",
            "CreationDateTime": "2018-07-07T12:00:00.1234567Z",
            "TestDataIndicator": "false",
            "ReconciliationIndicator": "true",
            "SenderParty": {
                "InternalID": {
                    "@schemeID": "CommunicationSystemID",
                    "@schemeAgencyID": "310",
                    "$title": "AAAA"
                }
            },
            "RecipientParty": {
                "InternalID": {
                    "@schemeID": "CommunicationSystemID",
                    "@schemeAgencyID": "310",
                    "$title": "ZZZZ"
                }
            },
            "BusinessScope": {
                "TypeCode": "3",
                "ID": "106"
            }
        },
        "ServiceRequestReplicationConfirmationMessage": {
            "BasicMessageHeader": {
                "ID": "SRQ_REQ_CONF"
            },
            "ServiceRequestInstance": {
                "@actionCode": "02",
                "ID": "4021788",
                "StatusText": "-2"
            }
        }
    }
}<br>

Step 2: JSON to XML converter with Json Prefix(glob) and XML namespace(http://sap.com/xi/SAPGlobal20/Global)

Step 3: Send the XML to C4C via SOAP adapter

Output XML which i am getting:

<?xml version='1.0' encoding='UTF-8'?>
<ServiceRequestReplicateConf xmlns:glob="http://sap.com/xi/SAPGlobal20/Global">
  <MessageHeader>
    <ID>MJTEST_CORE_TO_C4C</ID>
    <CreationDateTime>2018-07-07T12:00:00.1234567Z</CreationDateTime>
    <TestDataIndicator>false</TestDataIndicator>
    <ReconciliationIndicator>true</ReconciliationIndicator>
    <SenderParty>
      <InternalID schemeID="CommunicationSystemID" schemeAgencyID="310">AAAA</InternalID>
    </SenderParty>
    <RecipientParty>
      <InternalID schemeID="CommunicationSystemID" schemeAgencyID="310">ZZZZ</InternalID>
    </RecipientParty>
    <BusinessScope>
      <TypeCode>3</TypeCode>
      <ID>106</ID>
    </BusinessScope>
  </MessageHeader>
  <ServiceRequestReplicationConfirmationMessage>
    <BasicMessageHeader>
      <ID>SRQ_REQ_CONF</ID>
    </BasicMessageHeader>
    <ServiceRequestInstance actionCode="02">
      <ID>4021788</ID>
      <StatusText>-2</StatusText>
    </ServiceRequestInstance>
  </ServiceRequestReplicationConfirmationMessage>
</ServiceRequestReplicateConf>

What my requirement is :

In the below tags i need to add prefix 'glob' in the starting of the tag as shown from the Expected output xml in C4C.

<ServiceRequestReplicateConf xmlns:glob="http://sap.com/xi/SAPGlobal20/Global">
and 
</ServiceRequestReplicateConf>

Can you please help me in same?

Thanks,

Mary

RB777
Product and Topic Expert
Product and Topic Expert
0 Kudos

Hi Morten,

Thanks for the information.

But I was actually looking to add a prefix to the starting of the tag.

This i could achieve as posting below

Thanks,

Mary Jose

Accepted Solutions (0)

Answers (2)

Answers (2)

RB777
Product and Topic Expert
Product and Topic Expert

Hi Colleagues,

I could find out the answer which i am looking for.

I have modified the Step1 code with the below lines, by providing the prefix and starting tag in single quotes:

..................................................................................
....def builder = new JsonBuilder() 
      builder.'glob:ServiceRequestReplicateConf' { 
              MessageHeader { ......
....................................................................................

This gives me the expected output i need:

Output Json:

.........................................
{
    "glob:ServiceRequestReplicateConf": {
        "MessageHeader": {
.........................................

Output XML with prefix glob:

..............

<glob:ServiceRequestReplicateConf xmlns:glob="http://sap.com/xi/SAPGlobal20/Global">
................

P.S: Why I tried the approach which I took is, for Sender they don't have an XSD or general structure which I can map to C4C Inbound service structure. Hence tried this way.

Challenges I faced:

When I try with the answers which I get from Google, that doesn't support by JSONtoXML converter or groovy script. Also, I didn't find in Cloud Platform Integration(help.sap.com) documentation regarding any example or syntax which should be supported in cases like mine. I was basically stuck with adding JSON prefix(e.g.: glob in my example), namespace (e.g.: xmlns:glob="http://sap.com/xi/SAPGlobal20/Global" in my example) and also with a JSON element with both attribute and value(InternalID {'@schemeID'('CommunicationSystemID')'@schemeAgencyID'('310')'$title'('AAAA')}. Here, to denote attribute we have to use prefix '@' and for value we have to use prefix '$'.

Hope this helped colleagues who try to convert incoming JSON to Outgoing XML using JSON to XML converter in Groovy Script.

Thanks & Regards,

Mary Jose

mrbass
Participant
0 Kudos

You could do this if you want it dynamically from an existing XML template

def parseXML = new XmlSlurper(false,true).parse(xas)
def oSalesOrderCollection = new XmlSlurper(false,false).parse(oSalesOrder)
//This Will change and replace the header and yield over it children dynamically 
def oSalesOrderSOAPMarkup = new StreamingMarkupBuilder().bind {'glob:SalesOrderBundleMaintainRequest_sync'( 'xmlns:glob':'http://sap.com/xi/SAPGlobal20/Global' ){
                          mkp.yield oSalesOrderCollection.children()
                           }
                        } 
def xmlString = XmlUtil.serialize(oSalesOrderSOAPMarkup)
def xml = new XmlSlurper().parseText(xmlString)