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 Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  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.

Jitendra Bafna user avatar by
Jitendra Bafna
CORE ·
Dec. 19, 17 · Tutorial
Like (7)
Save
Tweet
Share
48.97K 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.

Popular on DZone

  • Top Authentication Trends to Watch Out for in 2023
  • SAST: How Code Analysis Tools Look for Security Flaws
  • Writing a Modern HTTP(S) Tunnel in Rust
  • Deploying Java Serverless Functions as AWS Lambda

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: