Showing results for 
Search instead for 
Did you mean: 

Generate JSON string using Groovy UDF in SAP CPI Mapping

0 Kudos

Hi Guys,

I am struggling to write a UDF in CPI mapping. My requirement is to get the 3 fields from source xml , combine them in a json string and pass it to the target xml field in JSON

The source xml is as below


these fields have to pass as JSON string into customrole_info field

[{“OrgUnit”: “<department1>”, “JobCode”: “<role1>”, “JobTitle”: “<title1>”, }, {“OrgUnit”: “<department2>”, “JobCode”: “<role2>”, “JobTitle”: “<title2>”, }]

Target xml is ,


any input is much appriciated.



Community Manager
Community Manager
0 Kudos

Hi and welcome to the SAP Community!

Thank you for visiting SAP Community to get answers to your questions. Since you're asking a question here for the first time, I recommend that you familiarize yourself with (if you haven't already), as it provides tips for preparing questions that draw responses from our members.

Should you wish, you can revise your question by selecting Actions, then Edit (although once someone answers your question, you'll lose the ability to edit the question -- but if that happens, you can leave more details in a comment).

Finally, if you're hoping to connect with readers, please consider adding a picture to your profile. Here's how you do it: By personalizing your profile with a photo of you, you encourage readers to respond.


SAP Community Moderator

Active Contributor
0 Kudos

Hi Vijay

What have you tried so far? And in what way didn't it work?



Accepted Solutions (0)

Answers (1)

Answers (1)

Former Member
0 Kudos

Hello Vijay,

I tried to answer this as per my understanding, please find the code for groovy script UDF(xmlTojson.groovy) below:

import groovy.json.JsonBuilder

def void xmlTojson(String[] department, String[] role, String[] title, Output output, MappingContext context){
    def json = []
    for(int i = 0; i < department.length; i++){
        String departmentStr = department[i]
        String roleStr = role[i]
        String titleStr = title[i]
        json.add([ OrgUnit : { departmentStr }, JobCode : { roleStr }, JobTitle : { titleStr } ])
    JsonBuilder builder = new JsonBuilder()
        json.collect { 
                OrgUnit: it.OrgUnit(), 
                JobCode: it.JobCode(), 
                JobTitle: it.JobTitle() 


Here is the mapping that I used:

I assumed that n number of the source fields should all be aggregated and mapped to a single target, if that is not the case then you'll have to change the occurrence of the target as for me it's 0..1 and along with that make sure you handle the context of source fields accordingly.

Here is the display queue for the test data I used

Here is the test data I used:

Please accept this answer as Best Answer if it was of any help to you!