Home  >  Article  >  Java  >  What is the way to convert a JSON object to XML format in Java?

What is the way to convert a JSON object to XML format in Java?

WBOY
WBOYforward
2023-08-26 20:53:201466browse

What is the way to convert a JSON object to XML format in Java?

JSON is a lightweight data exchange format, its format is similar to key-value pair. We can convert JSONObject to XML format using the org.json.XML class, which provides static methods for converting XML text to JSONObject and converting JSONObject to XML text. The method XML.toString()converts the JSON object into a well-formed XML string with standardized elements.

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"?--><?xml version="1.0" encoding="ISO-8859-15"?>
<root>
   <employee>
      <name>Raja</name>
      <technology>Java</technology>
      <age>30</age>
   </employee>
</root>

The above is the detailed content of What is the way to convert a JSON object to XML format in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete