Message Transformation from JSON to XML FreeMarker in WSO2 MI.

Message Transformation from JSON to XML FreeMarker in WSO2 MI.

FreeMarker is a Java-based template engine that allows you to generate text-based output (such as HTML, XML, JSON, etc.) dynamically. The integration of FreeMarker templates within WSO2 MI was introduced in version 4.0.0. WSO2 MI is an integration runtime that allows users to develop, deploy, and manage integrations in microservices architectures. Developers can generate dynamic content based on predefined templates within their integration flows.

JSON to XML

INPUTOUTPUT
              {     “Addresses”: [         {             “Title”: “Present Address”,             “street”: “Sainagar”,             “district”: “Hyderabad”,             “state”: “Telangana”,             “pincode”: “505001”         },         {             “Title”: “permeant Address”,             “street”: “Sai”,             “district”: “Karimnagar”,             “state”: “Telangana”,             “pincode”: “505001”         }     ],     “success”: true,     “result”: “SUCCESS” }    <root>    <TotalResults>2</TotalResults> <Addresses>     <Address>         <Title></Title>         <Address>Sainagar   Hyderabad</Address>         <State>Telangana-505001</State>     </Address>     <Address>         <Title>permeant Address</Title>         <Address>Sai   Karimnagar</Address>         <State>Telangana-505001</State>     </Address> </Addresses> <success>true</success> <result>SUCCESS</result> </root>

The below Freemarker template used for the transformation.

<root>

<TotalResults><#if payload.Addresses?has_content>${payload.Addresses?size}<#else>null</#if></TotalResults>

<Addresses>

<#list payload.Addresses as d>

     <Address>

       <Title><#if d.Title?has_content>${d.Title}<#else></#if></Title>

       <Address><#if d.street?has_content || d.district?has_content>${d.street!}   ${d.district!}<#else></#if></Address>

        <State><#if d.state?has_content || d.picode?has_content>${d.state! }-${d.pincode}<#else></#if></State>

     </Address>

</#list>

</Addresses>

<success><#if payload.success?has_content>${payload.success?c}<#else></#if></success>

<result><#if payload.result?has_content>${payload.result}<#else></#if></result> </root>

Create new project Right click on api > new > RestAPI > Create new arifact given required filelds as Name and context > Finish. 

Drag and drop the payload factory

Configure the properties:

  • Payload Format: Inline
  • MediaType: XML
  • Template Type: Freemarker
  • Place the above freemarker transformation code in payload.

Build and run the artifacts

  • Right-click FreemarkerTemplateCompositeExporter and click Export Project Artifacts and Run
  • You will see the following dialog box. Select the FreemarkerTemplateConfigs folder in the artifact list and click Finish.

Result:

For more information, please write to [email protected]