Convert a JSON object to XML format in Java?

A JSON is a lightweight data-interchange format and the format of JSON is like a key-value pair. We can convert a JSONObject into an XML format using org.json.XML class, this provides static methods to convert an XML text into a JSONObject and to convert a JSONObject into an XML text. The XML.toString() method convert a JSON object into a well-formed, element-normal XML string.


public static java.lang.String toString(java.lang.Object object) throws JSONException


import org.json.*;
public class JSONtoXMLTest {
   public static void main(String[] args) throws JSONException {
      String json = "{employee : { age:30, name : Raja, technology:Java}}";
      //Convert JSON to XML
      String xml = convert(json, "root"); // This method converts json object to xml string
   public static String convert(String json, String root) throws JSONException {
      JSONObject jsonObject = new JSONObject(json);
      String xml = "<?xml version=\"1.0\" encoding=\"ISO-8859-15\"?>\n<"+root+">" + XML.toString(jsonFileObject) + "</"+root+">";
      return xml;


<?xml version="1.0" encoding="ISO-8859-15"?>

Updated on: 04-Jul-2020

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started