Apache Camel – Convert JSON to XML

Maven Dependencies



Example Program

package com.dineshkrish;

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 JsonToXml {

	public static void main(String[] args) throws Exception {

		// creating the camel context
		CamelContext context = new DefaultCamelContext();

		try {
			context.addRoutes(new RouteBuilder() {

				public void configure() throws Exception {

					from("direct:start").process(new Processor() {
						public void process(Exchange exchange) throws Exception {

							// get the json
							String json = exchange.getIn().getBody(String.class);

							// transform json to xml
							JSONObject jsonObject = new JSONObject(json);
							String xml = XML.toString(jsonObject);

							// set the xml

			// start the context

			String json = "{\"employee\": {\r\n" + "    \"name\": \"Dinesh Krishnan\",\r\n" + "    \"id\": 101,\r\n"
					+ "    \"age\": 20\r\n" + "}}";


			// creating the producer template
			ProducerTemplate producerTemplate = context.createProducerTemplate();
			producerTemplate.sendBody("direct:start", json);

			// creating the consumer template
			ConsumerTemplate consumerTemplate = context.createConsumerTemplate();
			String xml = consumerTemplate.receiveBody("seda:end", String.class);

			System.out.println("-----------------JSON to XML---------------------");

			// 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.
{"employee": {
    "name": "Dinesh Krishnan",
    "id": 101,
    "age": 20
-----------------JSON to XML---------------------
<employee><name>Dinesh Krishnan</name><id>101</id><age>20</age></employee>

Hello, folks, I am a founder of dineshkrish.com. I love Java and Open source technologies, If you find my tutorials are useful, please consider making donations to these charities.