How to convert JSON to XML using Java

In this post, I am going to discuss how to convert JSON to XML using Java. Firstly we have to know what is JSON and XML.

1.JSON stands for JavaScript Object Notation, a plain text used for human-readable data interchange. JSON is straightforward to understand.
2.XML is an acronym of eXtensible Markup Language. It was similar to JSON and was used to transport and store data. XML is a mode of communication between different applications.

(Note: Here, I used Eclipse IDE.)

You can have a look at the vice-versa from here: How to convert XML to JSON in Java

Conversion of JSON to XML in Java

Prerequisites for converting JSON To XML:

Create a Maven project with the name conversion_json_project in Eclipse IDE.

Below are the next steps to follow.

    1. As the first step, You can find a package in src/test/java with the name coversion_json_project. If not, create a package with the name coversion_json_project in Eclipse IDE.
    2. In the second step, I created a java class file with the name readJSON in the above package having the main method in it.
    3. Create another java class file with the name Convert_JSON_TO_XML.
    4. After the above steps, download this jar file java-json.zip and extract the zip file you downloaded. Here are some steps to add an external jar file into your library.
      1. Right-click on project file(i.e,conversion_json_project) goto Build path.
      2. When you go to build-path, you can see the option add external archives.
      3. Now, add the java-json.jar file, and you find that jar file in referenced libraries.
    5. Now open pom.xml, which was present in the ‘target’ folder of the conversion_json_project.
    6. In pom.xml, rewrite code present in between the dependencies tag (i.e.,<dependencies></dependencies>) with the following code.
      <dependencies>
          <!-- https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple -->
      <dependency>
          <groupId>com.googlecode.json-simple</groupId>
          <artifactId>json-simple</artifactId>
          <version>1.1.1</version>
      </dependency>
      </dependencies>
      
    7. We also need a JSON file with data in JSON format. For that, I created a JSON file with the name read in the directory of    conversion_json_project. And the data in the read.json file is:
      {
       "firstName": "John",
       "lastName": "Kennedy",
       "address": [
        {
         "street": "abc",
         "city": "Hyderabad",
         "state": "TL"
        },
        {
         "street": "xyz",
         "city": "Chennai",
         "state": "TN"
        }
       ]
      }
    8. With the above steps, we gathered all prerequisites for converting JSON to XML.

Let us start coding for readJSON and Convert_JSON_TO_XML java class files:

  1. Open the readJSON java class file and write the below code.
    package conversion_json_project;
    import java.io.*;
    
    
    import org.json.simple.JSONObject;
    import org.json.simple.parser.JSONParser;
    import org.json.simple.parser.ParseException;
    public class readJSON {
    
      public static void main(String[] args) throws FileNotFoundException, IOException, ParseException {
        JSONParser jp=new JSONParser();
        JSONObject jo=new JSONObject();
        jo=(JSONObject) jp.parse(new FileReader("read.json"));
        String json_value=jo.toString();
        //System.out.println(json_value);
        Convert_JSON_TO_XML c= new Convert_JSON_TO_XML();
        //System.out.println(c.convert_json(json_value));
        String res=c.convert_json(json_value);
        File file=new File("xmldata.xml");
        if((!file.exists())) {
          file.createNewFile();
        }
        PrintWriter pw=new PrintWriter(file);
        pw.println(res);
        pw.close();
      }
    
    }
  2. In the above program, I imported predefined methods in java.io for file reading, writing, and printing the data in the file. And I also imported some required methods, classes in org.json.simple for our conversion of JSON to XML.
  3. In the main method, I created objects of JSONParser for parsing the data while reading that data present in read.json using FileReader at the same time type casting JSONParser to JSONObject.
  4. Here we performed type casting into JSONObject because JSONObject has a special method toString, which helps to convert the whole data in the read.json file into a string format.
  5. After getting the string format of JSON data, we pass the string as an argument of the Convert_JSON_TO_XML java class file constructor using the object of Convert_JSON_TO_XML. And store that result(i.e., in the above program, we stored it in ‘res’).
  6. And the code for Convert_JSON_TO_XML.java is:
    package conversion_json_project;
    import org.json.JSONObject;
    import org.json.XML;
    
    
    public class Convert_JSON_TO_XML {
        public static String convert_json(String json_value) {
            String xml = "";
            try {
                JSONObject jsoObject = new JSONObject(json_value);
                xml = xml + XML.toString(jsoObject);
            } catch (Exception e) {
                System.out.println(e);
            }
            xml = xml + "";
            return xml;
        }
    }
  7. I created an XML file as “xmldata.xml” using File class in java.io, and it creates only when the file with the same name was not present.
  8. Finally, I used PrintWriter class in java.io for writing the stored result(i.e., converted string from JSON to XML) into “xmldata.xml” and closed the PrintWriter class.

Output:

//we can find "xmldata.xml" file in the directory of conversion_json_project with converted string of json data into xml
//The xml data or string present in the "xmldata.xml" file is...
<firstName>John</firstName><lastName>Kennedy</lastName><address><city>Hyderabad</city><street>abc</street><state>TL</state></address><address><city>Chennai</city><street>xyz</street><state>TN</state></address>

Note:

  • I used my own names for packages, classes, and methods. You can change it as you like.
  • I threw some exceptions at line 10 in readJSON.java for exception handling. You can also use a try-catch block.

Leave a Reply

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