Professional Documents
Culture Documents
Community
Technical Articles
Roy Kiran
June 9, 2020 11 minute read
Update 10th July 2020 – Added functionality to convert numbers to String using the NUM_TO_STRING
parameter.
Introduction:
I was recently trying to convert XML To JSON in the below format in SAP 7.4 and also trying to remove
certain tags from the XML structure and force a few nodes as JSON Array.
[
{
record : [
{ key1: value1 }
]
},
{
record : [
{ key1: value1 },
{ key1: value2 }
]
https://blogs.sap.com/2020/06/09/conversion-of-xml-to-json-using-generic-java-mapping/?update=updated 1/25
12/23/2020 Conversion of XML to JSON using Generic Java Mapping | SAP Blogs
}
]
We can easily convert XML to JSON on the REST channel. However, there are many restrictions on it in SAP
PI/PO.
Besides, in SAP PO 7.5 we can easily remove a key name by listing the tags in ‘setIgnoredElements’ on REST
Receiver Channel. However, this liberty isn’t available on SAP PI versions 7.4 & below. The Custom XML to
JSON Conversion bean also doesn’t help much here, especially if you wish to remove a node from the JSON
structure. Hence, I have implemented a Generic Java Mapping that can be used to achieve this and many
other tasks.
This blog focus on XML to JSON conversion using Java Mapping and also provides the liberty to play around
with the structure.
Implementation:
You can directly download the zip le from here and unzip it.
This zip contains 2 JAR les. Import the 2 jar les in SAP ESR as Imported Archives.
Please note the Java mapping uses org.json.XML java library to convert XML to JSON, so if it’s not in your
SAP library, you will receive missing ‘org.json.XML’ error. So do import the orgXmlJson jar le also.
https://blogs.sap.com/2020/06/09/conversion-of-xml-to-json-using-generic-java-mapping/?update=updated 2/25
12/23/2020 Conversion of XML to JSON using Generic Java Mapping | SAP Blogs
https://blogs.sap.com/2020/06/09/conversion-of-xml-to-json-using-generic-java-mapping/?update=updated 3/25
12/23/2020 Conversion of XML to JSON using Generic Java Mapping | SAP Blogs
Step 4:- De ne Binding for the JAVA mapping in operation mapping as below:
https://blogs.sap.com/2020/06/09/conversion-of-xml-to-json-using-generic-java-mapping/?update=updated 4/25
12/23/2020 Conversion of XML to JSON using Generic Java Mapping | SAP Blogs
Step 5:- Assign values to these parameters in the Integrated Con guration as required
https://blogs.sap.com/2020/06/09/conversion-of-xml-to-json-using-generic-java-mapping/?update=updated 5/25
12/23/2020 Conversion of XML to JSON using Generic Java Mapping | SAP Blogs
Step 6:- (Optional) If you are using REST channel, don’t forget to set the data as JSON in the Receiver
channel
ARRAY_NODES:
This is of String data type.
All tags including the root tag that are to be converted into an array can be passed here as a list
separated by commas.
E.g. ARRAY_NODES = Root,node1,node4
If you don’t want to convert any node to array in JSON, then keep the eld blank.
HIDE_KEYS:
This is of String data type
If you wish to hide the tag name and pass only the equivalent values to JSON structure, then pass all
the tag names as a list separated by commas to this eld.
E.g. HIDE_KEYS = node2,root
If you don’t want to hide any keys in JSON, then keep the eld blank.
DELETE_ENTRY:
This is of String data type
https://blogs.sap.com/2020/06/09/conversion-of-xml-to-json-using-generic-java-mapping/?update=updated 6/25
12/23/2020 Conversion of XML to JSON using Generic Java Mapping | SAP Blogs
If you wish to delete a tag and its value from the JSON structure, then pass all such tag names as a
list separated by commas to this eld.
E.g. DELETE_ENTRY = node5,node6
If you don’t want to delete any entries, then keep the eld blank.
LAST_LEVEL_TO_KEEP:
This is of integer data type
If you wish to delete the initial tags from XML hierarchy and retain the child nodes, then pass the
level number to this eld
Value 0 implies to not delete any level. (default value)
Value 1 implies removing the root node completely from the structure and keep its child node in the
JSON structure.
E.g. LAST_LEVEL_TO_KEEP = 2 (This will remove rst 2 levels from the XML/JSON structure)
If you don’t want to delete any entries, then set the eld as 0.
NUM_TO_STRING:
This is of the boolean data type.
If you want to covert all the numbers to string in the output JSON structure, then set this variable as
‘true’.
Setting this to true will result in all the numbers (integer, oat, long, short, double) to be in double-
quotes in the output JSON format.
Default value is ‘false’.
Now let’s understand how you have to set the parameter values. Below are a few examples that will help you
understand the same.
Sample XML :
<ns0:Root_MT xmlns:ns0="https://namespace">
<node1>
<node2>
<node3>abc</node3>
<node4>xyz</node4>
<node5>123</node5>
</node2>
<node6/>
</node1>
<node1>
<node2>
<node3>abc</node3>
<node4>xyz</node4>
<node5>200.005</node5>
https://blogs.sap.com/2020/06/09/conversion-of-xml-to-json-using-generic-java-mapping/?update=updated 7/25
12/23/2020 Conversion of XML to JSON using Generic Java Mapping | SAP Blogs
</node2>
</node1>
</ns0:Root_MT>
ARRAY_NODES = “”
HIDE_KEYS = “”
DELETE_ENTRY = “”
LAST_LEVEL_TO_KEEP = 0
NUM_TO_STRING = false
{ "Root_MT":
{
"node1": [
{ "node2": {
"node3": "abc",
"node4": "xyz",
"node5": 123
},
"node6": ""
},
{ "node2": {
"node3": "abc",
"node4": "xyz",
"node5": 200.005
}
}
]
},
"xmlns:ns0"="https://namespace"
}
Example2: Hide the root tag and send data as JSON Array. Also, delete the namespace tag from the JSON
structure and set node5 as JSON Array
ARRAY_NODES = “Root_MT,node5”
https://blogs.sap.com/2020/06/09/conversion-of-xml-to-json-using-generic-java-mapping/?update=updated 8/25
12/23/2020 Conversion of XML to JSON using Generic Java Mapping | SAP Blogs
HIDE_KEYS = “Root_MT”
DELETE_ENTRY = “xmlns:ns0”
LAST_LEVEL_TO_KEEP = 0
NUM_TO_STRING = false
{ [
{
"node1": [
{ "node2": {
"node3": "abc",
"node4": "xyz",
"node5": 123
},
"node6": []
},
{ "node2": {
"node3": "abc",
"node4": "xyz",
"node5": 200.005
}
}
]
}
]
}
Example3: Remove the level 1 i.e the root tag level, always keep node1 as JSON Array (even if one record is
found) and hide node1 key and delete the namespace attribute. Also, convert the numbers to string format.
ARRAY_NODES = “node1”
HIDE_KEYS = “node1”
DELETE_ENTRY = “xmlns:ns0”
NUM_TO_STRING = true
[
{ "node2": {
"node3": "abc",
https://blogs.sap.com/2020/06/09/conversion-of-xml-to-json-using-generic-java-mapping/?update=updated 9/25
12/23/2020 Conversion of XML to JSON using Generic Java Mapping | SAP Blogs
"node4": "xyz",
"node5": "123"
},
"node6": ""
},
{ "node2": {
"node3": "abc",
"node4": "xyz",
"node5": "200.005"
}
}
]
Source Code:
If you are importing the code from the link above, you need not bother about the source code. But just for
your curiosity purpose and understanding provided the source code below. Do have a glance at it and
provide suggestions and feedback.
package com.convert;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;
import org.json.XML;
import org.json.JSONArray;
import org.json.JSONObject;
import com.sap.aii.mapping.api.AbstractTransformation;
import com.sap.aii.mapping.api.StreamTransformationException;
import com.sap.aii.mapping.api.TransformationInput;
import com.sap.aii.mapping.api.TransformationOutput;
public XML2JSON() {
this.array_nodes = array_nodes;
this.hide_keys = hide_keys;
this.delete_entry = delete_entry;
this.last_level_to_keep = last_level_to_keep;
this.num_to_string = num_to_string;
}
@Override
public void transform(TransformationInput transformationInput,
TransformationOutput transformationOutput)
throws StreamTransformationException {
/*
* This is the default method called by SAP PI Java mapping Input :
* InputStream and OutputStream objects
*/
https://blogs.sap.com/2020/06/09/conversion-of-xml-to-json-using-generic-java-mapping/?update=updated 11/25
12/23/2020 Conversion of XML to JSON using Generic Java Mapping | SAP Blogs
.getString("DELETE_ENTRY");
int last_level_to_keep = transformationInput.getInputParameters()
.getInt("LAST_LEVEL_TO_KEEP");
boolean num_to_string = Boolean.parseBoolean(transformationInput.getInputParameters()
.getString("NUM_TO_STRING"));
/*
* This method Input: InputStream and OutputStream objects
*/
try {
// Declare a String variable to store output json format
String jsonPrettyPrintString = "";
https://blogs.sap.com/2020/06/09/conversion-of-xml-to-json-using-generic-java-mapping/?update=updated 12/25
12/23/2020 Conversion of XML to JSON using Generic Java Mapping | SAP Blogs
https://blogs.sap.com/2020/06/09/conversion-of-xml-to-json-using-generic-java-mapping/?update=updated 13/25
12/23/2020 Conversion of XML to JSON using Generic Java Mapping | SAP Blogs
else {
byte[] bytes = jsonPrettyPrintString.toString().getBytes("UTF-8");
} catch (Exception e) {
// Handle all exceptions
if (getTrace() != null) {
getTrace().addDebugMessage(
"Exception while writing OutputPayload: IOException", e);
outputStream.write("{}".toString().getBytes("UTF-8"));
throw new StreamTransformationException(e.toString());
} else
e.printStackTrace();
}
}
try {
// Create an array of keyset to loop further
String arr[] = new String[jsonObj.keySet().size()];
int k = 0;
for (String key : jsonObj.keySet())
arr[k++] = key;
// If there are records to be deleted, remove them and move to next key
if (delete_entry.contains(key)) {
jsonObj.remove(key);
continue;
}
https://blogs.sap.com/2020/06/09/conversion-of-xml-to-json-using-generic-java-mapping/?update=updated 14/25
12/23/2020 Conversion of XML to JSON using Generic Java Mapping | SAP Blogs
return jsonObj;
}
// Get the key value from JSONObject using opt() and not get(), as it
// can also return null value.
Object obj = jsonObj.opt(key);
https://blogs.sap.com/2020/06/09/conversion-of-xml-to-json-using-generic-java-mapping/?update=updated 15/25
12/23/2020 Conversion of XML to JSON using Generic Java Mapping | SAP Blogs
// Check if last level as per input is reached and return the output
// string
if (current_level == last_level_to_keep - 1) {
// If instance is JSONObject, remove the key and return the output
// string
if (jsonObj.get(node) instanceof JSONObject) {
return jsonObj.getJSONObject(node).toString(2);
}
// If instance is JSONArray, remove the key and return the output
// string
else if (jsonObj.get(node) instanceof JSONArray) {
return jsonObj.getJSONArray(node).toString(2);
}
https://blogs.sap.com/2020/06/09/conversion-of-xml-to-json-using-generic-java-mapping/?update=updated 16/25
12/23/2020 Conversion of XML to JSON using Generic Java Mapping | SAP Blogs
// If both above cases fail, invalid level was provided and return
// empty string
return "{}";
}
// If its not the last level step in deeper one level and pass Object
// and incremented level index
else if (jsonObj.get(node) instanceof JSONObject) {
return deleteLevel(jsonObj.getJSONObject(node), ++current_level);
} else if (jsonObj.get(node) instanceof JSONArray) {
return deleteLevel(jsonObj.getJSONArray(node).getJSONObject(0),
++current_level);
}
Conclusion
This is how I handled my conversion using a generic and reusable custom java mapping that is able to
handle XML to JSON conversion. Hopefully, this piece of code helps those who have faced similar situations.
Please do let me know if you have handled this situation in any other optimized way!!
Anyone who wishes to edit the content or convert this JAVA mapping to a custom XML to JSON conversion
bean can please do the needful and share it…
And do hit the like button, if you found the blog useful..:)
Best Regards,
Kiran Roy
Alert Moderator
https://blogs.sap.com/2020/06/09/conversion-of-xml-to-json-using-generic-java-mapping/?update=updated 17/25
12/23/2020 Conversion of XML to JSON using Generic Java Mapping | SAP Blogs
Assigned tags
View more...
Related Questions
16 Comments
Apu Das
Nice blog. Weren’t you able to achieve this using REST adapter?
Like(0)
We are on SAPI 7.4. And unfortunately, couldn’t have this setup on the REST adapter.
Like(0)
https://blogs.sap.com/2020/06/09/conversion-of-xml-to-json-using-generic-java-mapping/?update=updated 18/25
12/23/2020 Conversion of XML to JSON using Generic Java Mapping | SAP Blogs
janardhan reddy
Hello Kiran,
I tried the same approach and everything is working ne but in the output JSON for few elds values are not
showing in string as it containing numbers. Could you please help how to handle for those elds.
Regards,
janardhan
Like(0)
Hi Janardhan,
Updated the blog and program to add number to string conversion functionality. Hope it helps now.
Regards,
Kiran Roy
Like(0)
Amarnath M
Hi
https://blogs.sap.com/2020/06/09/conversion-of-xml-to-json-using-generic-java-mapping/?update=updated 19/25
12/23/2020 Conversion of XML to JSON using Generic Java Mapping | SAP Blogs
Like(0)
Hi Amarnath,
You just have to pass RequestBody to ARRAY_NODES & that should work.
ARRAY_NODES : RequestBody
Regards,
Kiran Roy
Like(0)
Sukhdeep Singh
I have a requirement where i have to pass nal JSON(REST Receiver Channel) as an HASHBse64 converted
string in REST header custom property.
So was initially thinking to call REST adapter using UDF to get JSON le and then use UDF to HASH
conversion to provide string to another REST adapter. But now i had 2nd option by which i can avoid
duplication of rest channel. Will give it a go and provide feedback.
Cheers
Like(0)
Sukhdeep Singh
Hello Roy Kiran ,
https://blogs.sap.com/2020/06/09/conversion-of-xml-to-json-using-generic-java-mapping/?update=updated 20/25
12/23/2020 Conversion of XML to JSON using Generic Java Mapping | SAP Blogs
Can you look into converting functionality into UDF? Actually i am running into bit of problem as i have to
put converted JSON under target XML structure.
Regards
Like(0)
Hi Sukhdeep,
But if I understand your requirement correctly, based on your previous comments, you want to encode data
using BASE64 hashing before sending it to the receiver.
So post JSON conversion, try applying the hashing adapter module as mentioned here.
But to use this, you will have to install this custom adapter in SAP.
Regards,
Kiran Roy
Like(0)
Kasturika Phukan
Hi Kiran,
I have gone through all the examples but even for default value i.e. ARRAY_NODES =”” the same error I am
getting. Could you please suggest.
Regards
Kasturika Phukan
https://blogs.sap.com/2020/06/09/conversion-of-xml-to-json-using-generic-java-mapping/?update=updated 21/25
12/23/2020 Conversion of XML to JSON using Generic Java Mapping | SAP Blogs
Like(0)
Hi Kasturika,
Please perform the below checks… Either the le has not been downloaded correctly or you might have
mistakenly missed some con g step.
1. To check if the le is downloaded correctly, please check if XML2JSON.class & .java les both are present
and if you open the XML2JSON.java le, you should be able to see the full code… (Step 1)
2. Ensure you have con gured steps 3,4 & 5 correctly.
In case everything is ne & the problem yet persists, kindly send a screenshot of the error message you are
facing.
Regards,
Kiran Roy
Like(0)
Ejas Ahamed
Hi Kiran,
The json output is not well formed it is not as we create the data type in ESR,
https://blogs.sap.com/2020/06/09/conversion-of-xml-to-json-using-generic-java-mapping/?update=updated 22/25
12/23/2020 Conversion of XML to JSON using Generic Java Mapping | SAP Blogs
Like(0)
Abdul Hammed
Hello Roy,
i tried applying the same to Idoc XML conversion into JSON, but the segments & the eld positions are not
indent.
example:
MATMAS IDOC to JSON where the actual hierarchy is MAMTMAS – – IDOC – – EDIDC40 – – E1MARAM but
in output JSON after IDOC i’m getting E1MARAM at rst level instead of EDIDC40 and the elds inside also.
Like(1)
Functional Consultants
Hi Kiran,
XML to Json conversion is happening but elds positions are not indent, it is getting jumbled. Kindly
Suggest.
Regards,
Rajesh Ginka
Like(0)
Priyanka Sarode
Hey Kiran,
https://blogs.sap.com/2020/06/09/conversion-of-xml-to-json-using-generic-java-mapping/?update=updated 23/25
12/23/2020 Conversion of XML to JSON using Generic Java Mapping | SAP Blogs
I am using same and it’s working ne but on top of this we have requirement to convert JSON to base 64
format and then pass it as string to another JSON structure.
Thanks in advance.
Regards,
Priyanka
Like(0)
Vijayakumar Konna
Hi Kiran,
I can see, the code looks working but the elds sequence in JSON le are incorrect than compare with XML.
Here is the input and output JSON can you suggest.
XML Input :
<agreementIdenti er>
<agreementIdenti er1>
<agreementKey/>
</agreementIdenti er1>
<exclude/>
</agreementIdenti er>
<attribute1/>
<attribute2/>
<attribute3/>
<attribute4/>
JSON output :
{
“attribute4”: “”,
“agreementIdenti er”: {
“agreementIdenti er1”: [{“agreementKey”: “”}],
“exclude”: “”
},
“attribute1”: “”,
“attribute3”: “”,
https://blogs.sap.com/2020/06/09/conversion-of-xml-to-json-using-generic-java-mapping/?update=updated 24/25
12/23/2020 Conversion of XML to JSON using Generic Java Mapping | SAP Blogs
“attribute2”: “”
}
Find us on
Newsletter Support
https://blogs.sap.com/2020/06/09/conversion-of-xml-to-json-using-generic-java-mapping/?update=updated 25/25