Convert between JSON and XML in Java

By Arvind Rai, April 26, 2023
On this page, we will learn to convert JSON into XML and XML into JSON using org.json.JSONML class in our Java application. The org.json.JSONML provides static methods to convert an XML text into a JSONArray or JSONObject, and JSONArray or JSONObject into XML text using the JsonML transform.
Here on this page, we will convert an XML text into JSON as JSONArray and JSONObject. Then output JSON text will be converted into XML and we will see that we get the same XML.

1. Maven Dependency

ORG.JSON dependency is resolved as following.
<dependency>
  <groupId>org.json</groupId>
  <artifactId>json</artifactId>
  <version>20230227</version>
</dependency> 

2. XML into JSONArray

Find the static methods to convert XML text into JSONArray.
static JSONArray toJSONArray(String string) throws JSONException
static JSONArray toJSONArray(String string, boolean keepStrings) throws JSONException
static JSONArray toJSONArray(XMLTokener x) throws JSONException
static JSONArray toJSONArray(XMLTokener x, boolean keepStrings) throws JSONException 
The toJSONArray converts an XML string into JSONArray using the JsonML transform. Each XML tag is represented as a JSONArray in which the first element is the tag name. If the tag has attributes, then the second element will be JSONObject containing the name/value pairs. If the tag contains children, then strings and JSONArray will represent the child tags. Comments, prologs, DTDs are ignored.

Parameters:
string: The XML source string.
x: An XMLTokener of the XML source text.
keepStrings: If true, values will not be changed into Boolean or numeric values and will instead be left as strings.

Example:
Suppose we have following XML that needs to be converted into JSONArray.
<person created="20023-03-12T15:20" modified="20023-04-14T16:25">
  <firstName>Mahesh</firstName>
  <lastName>Sharma</lastName>
  <age>25</age>
  <address type="home">
    <village>XYZ Pur</village>
    <city>Varanasi</city>
    <state>UP</state>
    <postalCode>123456</postalCode>
  </address>
</person> 
Find the code.
String xml = "<person created=\"20023-03-12T15:20\" modified=\"20023-04-14T16:25\">\r\n"
	+ "  <firstName>Mahesh</firstName>\r\n"
	+ "  <lastName>Sharma</lastName>\r\n"
	+ "  <age>25</age>\r\n"
	+ "  <address type=\"home\">\r\n"
	+ "    <village>XYZ Pur</village>\r\n"
	+ "    <city>Varanasi</city>\r\n"
	+ "    <state>UP</state>\r\n"
	+ "    <postalCode>123456</postalCode>\r\n"
	+ "  </address>\r\n"
	+ "</person>";

JSONArray jsonArray = JSONML.toJSONArray(xml);
System.out.println(jsonArray.toString(3)); 
Output
[
   "person",
   {
      "created": "20023-03-12T15:20",
      "modified": "20023-04-14T16:25"
   },
   [
      "firstName",
      "Mahesh"
   ],
   [
      "lastName",
      "Sharma"
   ],
   [
      "age",
      25
   ],
   [
      "address",
      {"type": "home"},
      [
         "village",
         "XYZ Pur"
      ],
      [
         "city",
         "Varanasi"
      ],
      [
         "state",
         "UP"
      ],
      [
         "postalCode",
         123456
      ]
   ]
] 
We can pass XML string into XMLTokener.
JSONArray jsonArray = JSONML.toJSONArray(new XMLTokener(xml)); 
Using keepStrings value as true.
JSONArray jsonArray = JSONML.toJSONArray(xml, true);
JSONArray jsonArray = JSONML.toJSONArray(new XMLTokener(xml), true); 
For pretty printing of JSON, use indentFactor with JSONArray.toString. The indentFactor is the number of spaces to add to each level of indentation. Here we are using indentFactor as 3.
jsonArray.toString(3) 

3. XML into JSONObject

Find the static methods to convert XML text into JSONObject.
static JSONObject toJSONObject(String string) throws JSONException
static JSONObject toJSONObject(String string, boolean keepStrings) throws JSONException
static JSONObject toJSONObject(XMLTokener x) throws JSONException
static JSONObject toJSONObject(XMLTokener x, boolean keepStrings) throws JSONException 
The toJSONObject converts XML text into JSONObject using the JsonML transform. Each XML tag is represented as a JSONObject with a "tagName" property. If the tag has attributes, then the attributes will be in the JSONObject as properties. If the tag contains children, the object will have a "childNodes" property which will be an array of strings as JSONObjects. Comments, prologs, DTDs are ignored.

Parameters:
string: The XML source string.
x: An XMLTokener of the XML source text.
keepStrings: If true, values will not be changed into Boolean or numeric values and will instead be left as strings.

Example:
JSONObject jsonArray = JSONML.toJSONObject(xml);
System.out.println(jsonArray.toString(3)); 
We have taken same source XML from above example.
Find the Output.
{
   "created": "20023-03-12T15:20",
   "childNodes": [
      {
         "childNodes": ["Mahesh"],
         "tagName": "firstName"
      },
      {
         "childNodes": ["Sharma"],
         "tagName": "lastName"
      },
      {
         "childNodes": [25],
         "tagName": "age"
      },
      {
         "childNodes": [
            {
               "childNodes": ["XYZ Pur"],
               "tagName": "village"
            },
            {
               "childNodes": ["Varanasi"],
               "tagName": "city"
            },
            {
               "childNodes": ["UP"],
               "tagName": "state"
            },
            {
               "childNodes": [123456],
               "tagName": "postalCode"
            }
         ],
         "tagName": "address",
         "type": "home"
      }
   ],
   "modified": "20023-04-14T16:25",
   "tagName": "person"
} 

4. JSONArray into XML

Find the static method to convert JSONArray into XML text.
static String toString(JSONArray ja) throws JSONException 
Converts the JSONArray into XML text.
Example:
JSONArray jsonArray = new JSONArray(json);
String xml = JSONML.toString(jsonArray);
System.out.println(xml); 
We are using source json obtained in the output of above "XML into JSONArray" example.
Find the output.
<person created="20023-03-12T15:20" modified="20023-04-14T16:25">
	<firstName>Mahesh</firstName>
	<lastName>Sharma</lastName>
	<age>25</age>
	<address type="home">
		<village>XYZ Pur</village>
		<city>Varanasi</city>
		<state>UP</state>
		<postalCode>123456</postalCode>
	</address>
</person> 

5. JSONObject into XML

Find the static method to convert JSONObject into XML text.
static String toString(JSONObject jo) throws JSONException 
Converts the JSONObject into XML text.
Example:
JSONObject jsonObj = new JSONObject(json);
String xml = JSONML.toString(jsonObj);
System.out.println(xml); 
Use source json obtained in the output of above "XML into JSONObject" example.
Here we will get the same output XML as in above example.

6. Reference

POSTED BY
ARVIND RAI
ARVIND RAI







©2024 concretepage.com | Privacy Policy | Contact Us