Saturday, May 27, 2017

Convert JSON to XML using Java

This post will discuss on how you can convert json to xml using Java.

Language Used:
Java

Pom Dependency:
 <!-- https://mvnrepository.com/artifact/org.json/json -->  
 <dependency>  
   <groupId>org.json</groupId>  
   <artifactId>json</artifactId>  
   <version>20170516</version>  
 </dependency>  

Git Repo:
https://github.com/csanuragjain/extra/tree/master/convertJson2XML

Program:

main method:
      public static void main(String[] args) {  
           // TODO Auto-generated method stub  
           String jsonString="{\"name\":\"Virat\",\"sport\":\"cricket\",\"age\":25,\"id\":121,\"lastScores\":[72,23,57,54,36,74,17]}";  
           System.out.println(new Json2XML().json2XML(jsonString));  
      }  

How it works:
1) We call the method json2XML which we created passing the json to be converted
2) The return value of function contains the resulting xml

json2XML method:
      public String json2XML(String jsonString){  
           JSONObject json = new JSONObject(jsonString);  
           String xml = XML.toString(json);  
           return xml;  
      }  

How it works:
1) We pass the Json String to be converted into the JSONObject
2) We use the toString method of XML class passing the json object created in Step1
3) Step2 gives the resulting xml which is then returned.
4) If you want to give a root node for resulting xml then you can provide the root xml node as second argument in toString method from Step2

Full Program:
 package com.cooltrickshome;  
 import org.json.JSONObject;  
 import org.json.XML;  
 public class Json2XML {  
      /**  
       * @param args  
       */  
      public static void main(String[] args) {  
           // TODO Auto-generated method stub  
           String jsonString="{\"name\":\"Virat\",\"sport\":\"cricket\",\"age\":25,\"id\":121,\"lastScores\":[72,23,57,54,36,74,17]}";  
           System.out.println(new Json2XML().json2XML(jsonString));  
      }  
      public String json2XML(String jsonString){  
           JSONObject json = new JSONObject(jsonString);  
           String xml = XML.toString(json);  
           return xml;  
      }  
 }  

Input:
{"name":"Virat","sport":"cricket","age":25,"id":121,"lastScores":[77,72,23,57,54,36,74,17]}

Output:

<name>Virat</name><lastScores>77</lastScores><lastScores>72</lastScores><lastScores>23</lastScores><lastScores>57</lastScores><lastScores>54</lastScores><lastScores>36</lastScores><lastScores>74</lastScores><lastScores>17</lastScores><id>121</id><sport>cricket</sport><age>25</age>

Hope it helps :)

1 comment: