Hello everyone, In this post, you will learn How to Convert XML to JSON using Apache Camel. The example has been tested and shared in the post.

Maven Dependencies


Example Program

package com.dineshkrish.example6;
import org.apache.camel.CamelContext;
import org.apache.camel.ConsumerTemplate;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
import org.json.JSONObject;
import org.json.XML;
* @author Dinesh Krishnan
public class XmlToJson {
public static void main(String[] args) throws Exception {
// create a camel context
CamelContext context = new DefaultCamelContext();
try {
context.addRoutes(new RouteBuilder() {
public void configure() throws Exception {
.process(new Processor() {
public void process(Exchange exchange) throws Exception {
// get the content
String xml = exchange.getIn().getBody(String.class);
// traform from xml to json
byte[] encoded = xml.getBytes();
JSONObject xmlJSONObj = XML.toJSONObject(new String(encoded));
String json = xmlJSONObj.toString(4);
// set the content
// start the context
String xml = "<employee>\r\n" + "	<id>101</id>\r\n" + "	<name>Dinesh Krishnan</name>\r\n"
+ "	<age>20</age>\r\n" + "</employee>";
// creating the producer template
ProducerTemplate producerTemplate = context.createProducerTemplate();
producerTemplate.sendBody("direct:start", xml);
// creating the consumer template
ConsumerTemplate consumerTemplate = context.createConsumerTemplate();
String json = consumerTemplate.receiveBody("seda:end", String.class);
System.out.println("------------XML to JSON-------------");
// stop the context
} catch (Exception e) {


SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
<name>Dinesh Krishnan</name>
------------XML to JSON-------------
{"employee": {
"name": "Dinesh Krishnan",
"id": 101,
"age": 20

No responses yet

Leave a Reply

Your email address will not be published. Required fields are marked *