Mule Datamapper JSON to XML Transformation

573 views Asked by At

JSON Input Payload information, Where i have issue with.

{
"name": "xyz",
"city": "california",
"serialNumber": [ 
   "T2323" , 
   "T2332" 
]
}

Expected transformed Output Payload :

<COMPANY_ITEM_INFO>
     <COMPANY_NAME>xyz</COMPANY_NAME>
     <COMPANY_CITY>california</COMPANY_NAME>
     <Inv_Update SEGMENT="1"> 
         <SERIALNO>T2323</SERIALNO>  
     </Inv_Update SEGMENT="1">  
     <Inv_Update SEGMENT="1"> 
         <SERIALNO>T2332</SERIALNO>
     </Inv_Update SEGMENT="1">
</COMPANY_ITEM_INFO>

Actual Output received from Datamapper only 1 element as output.

<COMPANY_ITEM_INFO>
    <COMPANY_NAME>xyz</COMPANY_NAME>
    <COMPANY_CITY>california</COMPANY_NAME>
    <Inv_Update SEGMENT="1"> 
        <SERIALNO>T2323</SERIALNO> 
    </Inv_Update SEGMENT="1"> 
</COMPANY_ITEM_INFO>

Datamapper Code:

Foreach 'Object' - > 'COMPANY_ITEM_INFO'

//MEL
//START -> DO NOT REMOVE
output.__id = input.__id;
//END -> DO NOT REMOVE
output.COMPANY_NAME= input.name;
output.COMPANY_CITY= input.city;

ForEach 'serialNumber' -> 'Inv_Update'

//MEL
//START -> DO NOT REMOVE
output.__id = input.__id;
output.__parent_id = input.__id;
//END -> DO NOT REMOVE
output.SERIALNO = input.array;
1

There are 1 answers

8
David Dossot On BEST ANSWER

I know you're looking for a DataMapper solution but in case you're open to alternative, below is a Groovy implementation (since DataMapper is going away, now that Weave is coming, you should be open for options right?).

<json:json-to-object-transformer
    returnClass="java.lang.Object" />

<scripting:transformer>
  <scripting:script engine="groovy"><![CDATA[
    def writer = new StringWriter() 
    def xml = new groovy.xml.MarkupBuilder(writer)

    xml.COMPANY_ITEM_INFO { 
      COMPANY_NAME(payload.name) 
      COMPANY_CITY(payload.city) 

      payload.serialNumber.each { sn ->
        Inv_Update(SEGMENT: '1') {
          SERIALNO(sn)
        }
      }
    }

    result = writer.toString()
  ]]></scripting:script>
</scripting:transformer>