DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • How to Connect to Splunk Through Anypoint Studio in 10 Steps
  • Stop Poisoning Your Models: How I Built a CV Dataset Quality Toolkit I Can Reuse Forever
  • Advanced Auto Loader Patterns for Large-Scale JSON and Semi-Structured Data
  • From 13,000 to 20,000+ Endpoints: Architecting Forensics for the Remote Workforce

Trending

  • Every Cache Miss Is a Tiny Tax on Your Performance
  • The Missing `bandit` for AI Agents: How I Built a Static Analyzer for Prompt Injection
  • Building a Spring AI Assistant With MCP Servers: A Step-by-Step Tutorial
  • Identity in Action
  1. DZone
  2. Coding
  3. Languages
  4. Data Transformation: XML to JSON And JSON to XML With Apache Camel

Data Transformation: XML to JSON And JSON to XML With Apache Camel

In this tutorial, you will learn how to achieve data transformation by converting XML to JSON and JSON to XML with Apache Camel.

By 
Jitendra Bafna user avatar
Jitendra Bafna
·
Dec. 19, 17 · Tutorial
Likes (7)
Comment
Save
Tweet
Share
57.0K Views

Join the DZone community and get the full member experience.

Join For Free

1.0 Overview

Apache Camel provides a rich set of libraries to perform XML to JSON and JSON to XML transformation.

  • marshalling => converting from XML to JSON
  • un-marshaling => converting from JSON to XML.

2.0 Explicitly Instantiating the DataFormat

We need to instantiate the XmlJsonDataFormat from package org.apache.camel.dataformat.xmljson.XmlJsonDataFormat and make sure that camel-xmljson is added in your pom.xml or an installed camel-xmljson feature.

XmlJsonDataFormat xmlJsonFormat = new XmlJsonDataFormat();

2.1 XmlJsonDataFormat Property

XmlJsonDataFormat xmlJsonFormat = new XmlJsonDataFormat();
xmlJsonFormat.setEncoding("UTF-8");
xmlJsonFormat.setForceTopLevelObject(true);
xmlJsonFormat.setTrimSpaces(true);
xmlJsonFormat.setRootName("Employee");
xmlJsonFormat.setSkipNamespaces(true);
xmlJsonFormat.setRemoveNamespacePrefixes(true);
xmlJsonFormat.setExpandableProperties(Arrays.asList("d", "e"));

These properties are not mandatory and can be used when you want to tune the message.

2.2 Marshalling/Unmarshalling

Once XMLJsonDataFormat is instantiated, the next step is to use it as a parameter to  marshal() / unmarshal()  DSL elements.

Marshalling (converting from XML to JSON):

from("direct:unMarshalEmployeejson2xml")
                .unmarshal(xmlJsonFormat)
                .to("log:?level=INFO&showBody=true");

Un-Marshalling (converting from JSON to XML):

  from("direct:marshalEmployeexml2json")
                .marshal(xmlJsonFormat)
                .to("log:?level=INFO&showBody=true");

3.0 Defining Data Format In-Line

It is also possible to define the data format inline using the xmljson() DSL element:

  from("direct:unMarshalEmployeejson2xml")
                .unmarshal().xmljson()
                .to("log:?level=INFO&showBody=true");


from("direct:marshalEmployeexml2json")
                .marshal().xmljson()
                .to("log:?level=INFO&showBody=true");

It is also possible to pass Map to the inline method, as shown below.

Map<String, String> xmlJsonOptions = new HashMap<String, String>();

xmlJsonOptions.put(org.apache.camel.model.dataformat.XmlJsonDataFormat.ENCODING, "UTF-8");
xmlJsonOptions.put(org.apache.camel.model.dataformat.XmlJsonDataFormat.ROOT_NAME, "Employee");
xmlJsonOptions.put(org.apache.camel.model.dataformat.XmlJsonDataFormat.SKIP_NAMESPACES, "true");
xmlJsonOptions.put(org.apache.camel.model.dataformat.XmlJsonDataFormat.REMOVE_NAMESPACE_PREFIXES, "true");
xmlJsonOptions.put(org.apache.camel.model.dataformat.XmlJsonDataFormat.EXPANDABLE_PROPERTIES, "d e");

 from("direct:unMarshalEmployeejson2xml")
                .unmarshal().xmljson(xmlJsonOptions)
                .to("log:?level=INFO&showBody=true");

from("direct:marshalEmployeexml2json")
                .marshal().xmljson(xmlJsonOptions)
                .to("log:?level=INFO&showBody=true");

4.0 POM Dependency

We need to add some dependencies into the pom file to perform XML2JSON and JSON2XML transformation.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.learncamel</groupId>
    <artifactId>learncamel-transform</artifactId>
    <version>1.0-SNAPSHOT</version>
    <dependencies>
        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-core</artifactId>
            <version>2.19.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-test</artifactId>
            <version>2.19.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-xmljson</artifactId>
            <version>2.19.0</version>
        </dependency>
        <dependency>
            <groupId>xom</groupId>
            <artifactId>xom</artifactId>
            <version>1.2.5</version>
        </dependency>

        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.1.3</version>
        </dependency>

        <dependency>
            <groupId>net.sf.ezmorph</groupId>
            <artifactId>ezmorph</artifactId>
            <version>1.0.6</version>
        </dependency>

        <dependency>
            <groupId>commons-collections</groupId>
            <artifactId>commons-collections</artifactId>
            <version>3.2.1</version>
        </dependency>

        <dependency>
            <groupId>commons-beanutils</groupId>
            <artifactId>commons-beanutils</artifactId>
            <version>1.8.3</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.12</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.12</version>
        </dependency>
    </dependencies>
</project>

5.0 Code

5.1 Defining Route

package com.learncamel.route.xml2json;

import org.apache.camel.Route;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.dataformat.xmljson.XmlJsonDataFormat;

public class XML2JSONRoute extends RouteBuilder {

    public void configure() throws Exception {

        from("direct:marshalEmployeexml2json")
                .to("log:?level=INFO&showBody=true")
                .marshal().xmljson()
                .to("log:?level=INFO&showBody=true");


        final XmlJsonDataFormat xmlJsonFormat = new XmlJsonDataFormat();
        xmlJsonFormat.setRootName("Employee");

        from("direct:unMarshalEmployeejson2xml")
                //.unmarshal().xmljson()
                .unmarshal(xmlJsonFormat)
                .to("log:?level=INFO&showBody=true");

    }
}

5.2 Unit Test 

To test the above routes, you can define unit test cases and you will require the camel-test feature installed, or it can be added into the pom.xml dependency.

package com.learncamel.route.xml2json;

import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.test.junit4.CamelTestSupport;
import org.junit.Test;


public class XML2JSONRouteTest extends CamelTestSupport {

    @Override
    protected RouteBuilder createRouteBuilder() throws Exception {
        return new XML2JSONRoute();
    }

    @Test
    public void marshalEmployeeJSON2XML(){

        String expected = "{\"id\":\"123 \",\"name\":\"ABC\",\"type\":\"senior\"}";
        String request = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +
                "<Employee><id>123 </id><name>ABC</name><type>senior</type></Employee>\r\n";

        final String response = template.requestBody("direct:marshalEmployeexml2json", request, String.class);
        System.out.println("response is : " + response);

        assertEquals(expected, response);

    }

    @Test
    public void unMarshalEmployeeJSON2XML(){

        final String request = "{\"name\":\"ABC\",\"id\":\"123 \",\"type\":\"senior\"}";

        final String response = template.requestBody("direct:unMarshalEmployeejson2xml", request, String.class);
        System.out.println("response is : " + response);
        String expected = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +
                "<Employee><id>123 </id><name>ABC</name><type>senior</type></Employee>\r\n";
        assertEquals(expected, response);

    }
}

Now, you know how to convert XML to JSON and JSON to XML with Apache Camel.

JSON XML Apache Camel Data (computing)

Opinions expressed by DZone contributors are their own.

Related

  • How to Connect to Splunk Through Anypoint Studio in 10 Steps
  • Stop Poisoning Your Models: How I Built a CV Dataset Quality Toolkit I Can Reuse Forever
  • Advanced Auto Loader Patterns for Large-Scale JSON and Semi-Structured Data
  • From 13,000 to 20,000+ Endpoints: Architecting Forensics for the Remote Workforce

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook