How to Convert JSON into XML using Java?

How to Convert JSON into XML using Java?

XML is a markup language that is used to store data. JSON is a lightweight data-interchange format that is used to exchange data from client to server. Both XML and JSON are similar to HTML in java.

If you have ever had the need of converting XML to JSON in Java, you have probably come across the following libraries:

  • json-lib
  • jettison
  • xmlbeans
  • Xstream
  • Jackson

and many more.

Which one to use depends on many factors like complexity of your XML, size of your JSON, performance and many more.

In this article, we will see how to convert XML to JSON using the Jackson library. Why Jackson? Jackson is one of the most widely used JSON processing libraries. It has a wide variety of features and is very easy to use. Additionally, we will use Jackson XML module, which adds additional support for XML specific constructs such as:

  • XML attributes
  • XML namespaces
  • XML text

Convert XML to JSON

Let’s create a simple Java program that converts an XML document into a JSON object.

We will be using the following XML document, which is an API response from smashfly:

<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
  <book>
    <title>Everyday Italian</title>
    <author>Giada De Laurentiis</author>
    <year>2005</year>
    <price>30.00</price>
  </book>
  <book>
    <title>Harry Potter and the Half-Blood Prince</title>
    <author>J K. Rowling</author>
    <year>2005</year>
    <price>29.99</price>
  </book>
  <book>
    <title>XQuery Kick Start</title>
    <author>James McGovern</author>
    <author>Per Bothner</author>
    <author>Kurt Cagle</author>
    <author>James Linn</author>
    <author>Vaidyanathan Nagarajan</author>
    <year>2003</year>
    <price>49.99</price>
  </book>
  <book>
    <title>Learning XML</title>
    <author>Erik T. Ray</author>
    <year>2003</year>
    <price>39.95</price>
  </book>
</bookstore>

We will be using the following Maven dependencies:

<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-xml</artifactId>
    <version>2.9.0</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.0</version>
</dependency>

Here is our Java program:

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import java.io.File;
 
public class XmlToJson {
 
   public static void main(String[] args) throws Exception {
 
      File xmlFile = new File("books.xml");
      ObjectMapper xmlMapper = new XmlMapper();
      ObjectMapper jsonMapper = new ObjectMapper();
       // convert xml to json
      String jsonString = xmlMapper.writeValueAsString(xmlFile);
       // convert json to xml
      String xmlString = jsonMapper.writeValueAsString(jsonString);
 
      System.out.println(jsonString);
      System.out.println(xmlString);
   }
}

Output

{"bookstore":{"book":[{"title":"Everyday Italian","author":"Giada De Laurentiis","year":"2005","price":"30.00"},{"title":"Harry Potter and the Half-Blood Prince","author":"J K. Rowling","year":"2005","price":"29.99"},{"title":"XQuery Kick Start","author":["James McGovern","Per Bothner","Kurt Cagle","James Linn","Vaidyanathan Nagarajan"],"year":"2003","price":"49.99"},{"title":"Learning XML","author":"Erik T. Ray","year":"2003","price":"39.95"}]}}
<bookstore><book><title>Everyday Italian</bookstore></book></title>

Can we convert XML to JSON using Java?

Yes, we can convert XML to JSON in Java. There are many ways to do this, but one popular way is to use the Jackson library.

Jackson is a powerful library for parsing and generating JSON. It has a wide variety of features, making it a great choice for this task.

To use Jackson to convert XML to JSON, we first need to create a XmlMapper instance. We can then use the readValue and writeValue methods to convert between XML and JSON.

Here is a simple example:

String xml = "<root><foo>bar</foo><baz>qux</baz></root>"; 
XmlMapper xmlMapper = new XmlMapper(); 
Map<String, Object> map = xmlMapper.readValue(xml, new TypeReference<Map<String, Object>>(){}); 
String json = xmlMapper.writeValueAsString(map);

In this example, we first create an XML string. We then create an XmlMapper instance and use it to parse the XML string into a Map. Finally, we use the XmlMapper to generate a JSON string from the Map.

This is just a simple example, but the Jackson library is very flexible and can be used to convert between XML and JSON in a variety of ways.

How do I convert a file to JSON?

If you have a file that you need to convert to JSON, there are a few different ways that you can go about doing this. One way is to use a online converter, such as json-convert.com. Another way is to use a tool like the JSON Converter from Code Beautify.

Both of these methods are fairly simple and only require you to upload your file to be converted. Once your file is converted, you will be able to download it as a JSON file.

If you need to convert a JSON file back to a regular file, you can use a tool like the JSON to CSV Converter from Code Beautify. This converter will take your JSON file and turn it back into a CSV file.

Can we replace XML with JSON?

As the world of data moves ever forward, the question of whether XML or JSON is the better format for storing and transferring data has come up time and time again. While XML has been the standard for some time now, JSON is becoming increasingly popular as an alternative (and is being used by a lot of microservice APIs like freecurrencyapi.com. So, can we replace XML with JSON?

There are a few key differences between XML and JSON that make JSON a more attractive option for many applications. First, JSON is less verbose than XML. This means that it takes up less space and is easier to read. Second, JSON can be parsed much faster than XML. This is because JSON uses a simpler data model that is easier for computers to process.

So, why not replace XML with JSON? There are a few reasons. First, XML is still widely used and understood. Second, JSON does not support some of the features that XML does, such as comments and processing instructions. Finally, JSON is not as well suited for storing large amounts of data as XML is.

So, while JSON may be a better option for some applications, XML is still the best choice for others. It really depends on your specific needs.

Is XML and JSON file the same?

XML and JSON are both markup languages that are used to store data. They are both similar in that they are text-based and can be read by humans. However, they are different in how they are structured. XML is a markup language that is made up of tags. JSON is a data-interchange format that is made up of key-value pairs.

Share this post

Comments (2)

  • Valentyn Reply

    Underscore-java library has methods U.xmlToJson(xml) and U.jsonToXml(json)

    April 7, 2023 at 2:07 AM
  • Valentyn Kolesnikov Reply

    Underscore-java library has method U.xmlToJson(xml)

    June 29, 2023 at 4:31 PM

Leave a Reply

Your email address will not be published. Required fields are marked *