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

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

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

Related

  • How to Convert CSV to XML in Java
  • Dataweave Interview Question Using Map and Reduce
  • Working With Data in Microservices
  • How to Convert XLS to XLSX in Java

Trending

  • Role of Cloud Architecture in Conversational AI
  • How to Create a Successful API Ecosystem
  • A Complete Guide to Modern AI Developer Tools
  • Integrating Security as Code: A Necessity for DevSecOps
  1. DZone
  2. Coding
  3. Languages
  4. How to Convert JSON to XML or XML to JSON in Java

How to Convert JSON to XML or XML to JSON in Java

Learn how to easily convert a JSON object to XML or XML to JSON using APIs in Java.

By 
Brian O'Neill user avatar
Brian O'Neill
DZone Core CORE ·
Jun. 24, 21 · Tutorial
Likes (1)
Comment
Save
Tweet
Share
11.0K Views

Join the DZone community and get the full member experience.

Join For Free

Understanding how to convert between complex file types will allow you to optimize and perfect your operations, ensuring your data is always in the appropriate form. The two formats featured in today’s tutorial are JSON and XML. Both formats are widely used in web-based applications, but one may be more ideal than the other for certain objects. JavaScript Object Notation (JSON) is defined as an open standard file and data-interchange format that uses human-readable text to store and exchange data. It was initially developed from JavaScript, but as a language-independent format it can be used in many different programming languages. Due to its versatility, efficient design, and low cost, JSON has become a go-to for many businesses. 

Our other format, Extensible Markup Language (XML), is similar to JSON in that they both are easy to read, create, and decode. However, XML uses prescribed tags that divide information according to its traits and has limiting factors associated with characters (i.e. !”*(), etc.). While this option may contain a higher word count due to the tags, it does allow for more precision in how data is read by the computer, including improved metadata usability, which is unavailable in JSON. 

So, what does all this mean in terms of which option you should use? The answer is: it depends on the type of project you are working with. If it is a browser-based project, JSON is generally the best choice, while XML is best suited for server-based projects. No matter which format you choose, we have you covered with an easy way to move between the two. By utilizing the following APIs in Java, you will be able to automatically convert JSON to XML or XML to JSON with very little effort on your end.

To begin the process, we will install Maven by adding a reference to the repository in pom.xml:

Java
 
<repositories>
    <repository>
        <id>jitpack.io</id>
        <url>https://jitpack.io</url>
    </repository>
</repositories>


Then, we will add a reference to the dependency:

Java
 
<dependencies>
<dependency>
    <groupId>com.github.Cloudmersive</groupId>
    <artifactId>Cloudmersive.APIClient.Java</artifactId>
    <version>v3.90</version>
</dependency>
</dependencies>


Once the installation is complete, we are ready to call our first conversion function, which will be converting from JSON to XML:

Java
 
// Import classes:
//import com.cloudmersive.client.invoker.ApiClient;
//import com.cloudmersive.client.invoker.ApiException;
//import com.cloudmersive.client.invoker.Configuration;
//import com.cloudmersive.client.invoker.auth.*;
//import com.cloudmersive.client.ConvertDataApi;

ApiClient defaultClient = Configuration.getDefaultApiClient();

// Configure API key authorization: Apikey
ApiKeyAuth Apikey = (ApiKeyAuth) defaultClient.getAuthentication("Apikey");
Apikey.setApiKey("YOUR API KEY");
// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
//Apikey.setApiKeyPrefix("Token");

ConvertDataApi apiInstance = new ConvertDataApi();
Object jsonObject = null; // Object | Input JSON to convert to XML
try {
    byte[] result = apiInstance.convertDataJsonToXml(jsonObject);
    System.out.println(result);
} catch (ApiException e) {
    System.err.println("Exception when calling ConvertDataApi#convertDataJsonToXml");
    e.printStackTrace();
}


To ensure the operation is successful, you will need to input the following parameters:

  • JSON Object – the JSON object you wish to convert.
  • API Key – your personal API key. If you need to obtain a personal API key, you can do so by register for a free account on the Cloudmersive website; this will provide 800 monthly calls across any of our APIs.

Alternatively, if you need to convert XML to JSON, you simply need to input your target XML file and API key into the following code:

Java
 
// Import classes:
//import com.cloudmersive.client.invoker.ApiClient;
//import com.cloudmersive.client.invoker.ApiException;
//import com.cloudmersive.client.invoker.Configuration;
//import com.cloudmersive.client.invoker.auth.*;
//import com.cloudmersive.client.ConvertDataApi;

ApiClient defaultClient = Configuration.getDefaultApiClient();

// Configure API key authorization: Apikey
ApiKeyAuth Apikey = (ApiKeyAuth) defaultClient.getAuthentication("Apikey");
Apikey.setApiKey("YOUR API KEY");
// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
//Apikey.setApiKeyPrefix("Token");

ConvertDataApi apiInstance = new ConvertDataApi();
File inputFile = new File("/path/to/inputfile"); // File | Input file to perform the operation on.
try {
    Object result = apiInstance.convertDataXmlToJson(inputFile);
    System.out.println(result);
} catch (ApiException e) {
    System.err.println("Exception when calling ConvertDataApi#convertDataXmlToJson");
    e.printStackTrace();
}


These tools will provide a quick and efficient way to move between these two popular data formats, ensuring you don’t miss a beat if you need to shift from one to the other.

JSON XML Java (programming language) Convert (command)

Opinions expressed by DZone contributors are their own.

Related

  • How to Convert CSV to XML in Java
  • Dataweave Interview Question Using Map and Reduce
  • Working With Data in Microservices
  • How to Convert XLS to XLSX in Java

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!