Convert a JSON object to XML format in Java?

JavaJSONObject Oriented ProgrammingProgramming

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.

Syntax

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

Example

import java.io.*;
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
      System.out.println(xml);
   }
   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;
   }
}

Output

<?xml version="1.0" encoding="ISO-8859-15"?>
<root>
   <employee>
      <name>Raja</name>
      <technology>Java</technology>
      <age>30</age>
   </employee>
</root>
raja
Published on 18-Sep-2019 12:00:05
Advertisements