Convert XML to JSON using Mule Custom Transformer

979 views Asked by At

Hi I am working with Mule Studio and I want to create a Custom Transformer which will convert XML to Json using Google Gson Library. So in this case i have to add a Java Transformer component and i have to write a custom code for that. But the problem i am facing is i am overriding the method which accepts Input parameter as Object thats the only way i think or is their any other way which will accept Input Parameter as a XMl String. Please share a code to make it workable.

public class Transfomer extends AbstractTransformer { protected Object doTransform(Object src, String enc) throws TransformerException { // TODO Auto-generated method stub
return null; } }

3

There are 3 answers

1
David Dossot On BEST ANSWER

Take a look at an existing transformer: https://github.com/mulesoft/mule/blob/mule-3.x/modules/xml/src/main/java/org/mule/module/xml/transformer/XmlPrettyPrinter.java

  • See how in the constructor the accepted source types are registered, like with: registerSourceType(DataTypeFactory.create(org.dom4j.Document.class));
  • See how in the doTransform method the generic Object src is converted.
0
Srinivas On

Setting Dataweave output as application/json does the automatically. However when you do JSON to XML you might have to make sure the JSON can be converted to XML form with root element and member elements within.

0
Rajnish Kumar Jha On

You can use either XML to JSON transformer from the Mule palette to the Mule flows.

 <json:xml-to-json-transformer doc:name="XML to JSON"/>

OR

Use DataWeave Transformation:

 <dw:transform-message doc:name="Transform Message">
             <dw:set-payload><![CDATA[%dw 1.0
 %output application/json
 ---
 payload]]></dw:set-payload>
         </dw:transform-message>