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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

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

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • How to Connect to Splunk Through Anypoint Studio in 10 Steps
  • Loading XML into MongoDB
  • Modify JSON Data in Postgres and Hibernate 6
  • Exploring JSON Schema for Form Validation in Web Components

Trending

  • SQL Server Index Optimization Strategies: Best Practices with Ola Hallengren’s Scripts
  • Rust and WebAssembly: Unlocking High-Performance Web Apps
  • Power BI Embedded Analytics — Part 2: Power BI Embedded Overview
  • Integrating Jenkins With Playwright TypeScript: A Complete Guide
  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
DZone Core CORE ·
Dec. 19, 17 · Tutorial
Likes (7)
Comment
Save
Tweet
Share
55.7K 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
  • Loading XML into MongoDB
  • Modify JSON Data in Postgres and Hibernate 6
  • Exploring JSON Schema for Form Validation in Web Components

Partner Resources

×

Comments
Oops! Something Went Wrong

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

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!