How to Convert XML to JSON with Java

As the “most popular data interchange format” debate rages on into a new decade, we’re not here to take sides: both XML and JSON have their respective advantages, and our APIs can help you make either conversion as a cloud service. In this article, we’ll demonstrate an XML to JSON conversion API that you can easily utilize by structuring your API call with complementary Java code snippets provided below. To access this API, you’ll just need to register a free account on our website to get your API key (and with that key, you’ll gain access to dozens of additional Cloudmersive APIs — including our JSON to XML conversion).

Beginning with Java SDK installation (with Maven), let’s add a reference to the repository in pom.xml:

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

And let’s complete installation by adding another reference to the dependency in pom.xml:

<dependencies>
<dependency>
<groupId>com.github.Cloudmersive</groupId>
<artifactId>Cloudmersive.APIClient.Java</artifactId>
<version>v4.25</version>
</dependency>
</dependencies>

Now let’s add the import classes to the top of our file and call the API. Your XML input can be included in either string or file path format:

// 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();
}

Poof — all done, no more coding required. Check out more of our demo articles to find additional APIs that might suit your needs.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Cloudmersive

Cloudmersive

There’s an API for that. Cloudmersive is a leader in Highly Scalable Cloud APIs.