Home > Java > javaTutorial > 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
Release: 2023-08-26 20:53:20
forward
1511 people have browsed it

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
Copy after login

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;
   }
}
Copy after login

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>
Copy after login

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template