How to convert JSON to XML format in Java
Jumping back and forth between JSON and XML can be just as easy as is it helpful if you know the right trick. And that is the subject of today’s post. Let’s dive right into the process.
Our first step is to install our API library via Jitpack: add the following references in your pom.xml file.
Repository reference
<repositories>
<repository>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
</repository>
</repositories>
Dependency reference
<dependencies>
<dependency>
<groupId>com.github.Cloudmersive</groupId>
<artifactId>Cloudmersive.APIClient.Java</artifactId>
<version>v3.34</version>
</dependency>
</dependencies>
With that done, all that’s left is to call convertDataJsonToXml and provide a JSON file to convert.
// 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: ApikeyApiKeyAuth 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 XMLtry {byte[] result = apiInstance.convertDataJsonToXml(jsonObject);System.out.println(result);} catch (ApiException e) {System.err.println("Exception when calling ConvertDataApi#convertDataJsonToXml");e.printStackTrace();}
Elementary, my dear Watson! No, please don’t leave. You can reverse the process by calling convertDataXmlToJson instead. There are also over a hundred other similar functions available in this same API, so be sure to check them out. Just think of all the time you will save.