Jump to content

How to Convert JSON to XML in Java

+ 1
  tmo9d's Photo
Posted Sep 28 2009 09:09 AM

Use json-lib, a library which adds JSON support to any Java program. json-lib provides an XMLSerializer which can be used to output XML from a JSON object.

1. Add these dependencies to your project:
    <dependency>
    	<groupId>net.sf.json-lib</groupId>
    	<artifactId>json-lib</artifactId>
    	<version>2.3</version>
    	<type>jar</type>
    	<classifier>jdk15</classifier>
    	<scope>compile</scope>
    </dependency>
    <dependency>
    	<groupId>org.apache.commons</groupId>
    	<artifactId>commons-io</artifactId>
    	<version>1.3.2</version>
    	<type>jar</type>
    	<scope>compile</scope>
    </dependency>
    <dependency>
    	<groupId>xom</groupId>
    	<artifactId>xom</artifactId>
    	<version>1.1</version>
    </dependency>


What does this mean? See How to Add a Dependency to a Java Project

2. Put the following JSON sample in your classpath:
{'foo':'bar',
 'coolness':2.0,
 'altitude':39000,
 'pilot':{'firstName':'Buzz',
      	  'lastName':'Aldrin'},
 'mission':'apollo 11'}


3. Load the resource from the classpath, parse this JSON, and convert it to XML with the following class:
package com.discursive.answers;

import java.io.InputStream;

import net.sf.json.JSON;
import net.sf.json.JSONSerializer;
import net.sf.json.xml.JSONTypes;
import net.sf.json.xml.XMLSerializer;

import org.apache.commons.io.IOUtils;

public class ConvertJSONtoXML {

	public static void main(String[] args) throws Exception {
		InputStream is = 
			ConvertJSONtoXML.class.getResourceAsStream("sample-json.txt");
		String jsonData = IOUtils.toString(is);
		
		XMLSerializer serializer = new XMLSerializer(); 
		JSON json = JSONSerializer.toJSON( jsonData ); 
		String xml = serializer.write( json );  
		System.out.println(xml);  		
		
	}
}


4. The previous class will produce the following XML output:

<?xml version="1.0" encoding="UTF-8"?>
<o>
  <altitude type="number">39000</altitude>
  <coolness type="number">2.0</coolness>
  <foo type="string">bar</foo>
  <mission type="string">apollo 11</mission>
  <pilot class="object">
    <firstName type="string">Buzz</firstName>
    <lastName type="string">Aldrin</lastName>
  </pilot>
</o>


5. To get rid of the type hints, use this code instead:

package com.discursive.answers;

import java.io.InputStream;

import net.sf.json.JSON;
import net.sf.json.JSONSerializer;
import net.sf.json.xml.JSONTypes;
import net.sf.json.xml.XMLSerializer;

import org.apache.commons.io.IOUtils;

public class ConvertJSONtoXMLNoHints {

	public static void main(String[] args) throws Exception {
		InputStream is = 
			ConvertJSONtoXMLNoHints.class.getResourceAsStream("sample-json.txt");
		String jsonData = IOUtils.toString(is);
		
		XMLSerializer serializer = new XMLSerializer(); 
		JSON json = JSONSerializer.toJSON( jsonData ); 
		serializer.setTypeHintsEnabled(false);
		String xml = serializer.write( json );  
		System.out.println(xml);  		
		
	}
}


6. The previous class will produce the following XML without type hints:

<?xml version="1.0" encoding="UTF-8"?>
<o>
  <altitude>39000</altitude>
  <coolness>2.0</coolness>
  <foo>bar</foo>
  <mission>apollo 11</mission>
  <pilot>
    <firstName>Buzz</firstName>
    <lastName>Aldrin</lastName>
  </pilot>
</o>


7. "o" isn't a very friendly root node name, is it? To change the root node name, use the following code:

package com.discursive.answers;

import java.io.InputStream;

import net.sf.json.JSON;
import net.sf.json.JSONSerializer;
import net.sf.json.xml.JSONTypes;
import net.sf.json.xml.XMLSerializer;

import org.apache.commons.io.IOUtils;

public class ConvertJSONtoXMLSetRoot {

	public static void main(String[] args) throws Exception {
		InputStream is = 
			ConvertJSONtoXMLNoHints.class.getResourceAsStream("sample-json.txt");
		String jsonData = IOUtils.toString(is);
		
		XMLSerializer serializer = new XMLSerializer(); 
		JSON json = JSONSerializer.toJSON( jsonData ); 
		serializer.setRootName("SampleJSON");
		serializer.setTypeHintsEnabled(false);
		String xml = serializer.write( json );  
		System.out.println(xml);  		
		
	}
}


8. This previous class will produce the following XML:

<?xml version="1.0" encoding="UTF-8"?>
<SampleJSON>
  <altitude>39000</altitude>
  <coolness>2.0</coolness>
  <foo>bar</foo>
  <mission>apollo 11</mission>
  <pilot>
    <firstName>Buzz</firstName>
    <lastName>Aldrin</lastName>
  </pilot>
</SampleJSON>


This sample project is available on GitHub here: http://github.com/to...le-json-parsing

For more information about the json-lib project, see JSON-LIB project page

Java and XML

Learn more about this topic from Java and XML, 3rd Edition.

This new edition shows you how to cut through all the hype about XML and put it to work. You'll learn how to use the APIs, tools, and tricks of XML to build real-world applications. After two chapters on XML basics, the rest of the book focuses on using XML from your Java applications. The result is a new approach to managing information that touches everything from configuration files to web sites.

See what you'll learn


Tags:
1 Subscribe


6 Replies

 : Jan 27 2010 10:31 PM
When I try to convert json array, I am getting extra <e> element in xml

JSON:
{"company":"Info Corp", "employees":[{"name":"emp1"},{"name":"emp2"}]}

Converted XML:
<o>
<company>Info Corp</company>
<employees>
<e><name>emp1</name></e>
<e><name>emp2</name></e>
</employees>
</o>

Expected result
<o>
<company>Info Corp</company>
<employees>
<name>emp1</name>
<name>emp2</name>
</employees>
</o>

Please suggest solution how to filter out <e> element
0
  ldd88's Photo
Posted Dec 29 2011 06:24 AM

you can change your JSON (and remove the curly brackets inside employees):
{"company":"Info Corp", "employees":[{"name":"emp1"},{"name":"emp2"}]}
to:
{"company":"Info Corp", "employees":["name":"emp1","name":"emp2"]}
0
  liuxDiego's Photo
Posted May 24 2012 04:04 PM

Thanks!!!!

I have noticed that the XML tags are sorted alphabetically, Is there any way to keep the same order?

Ex:
"{\"name\":\"json\",\"bool\":true,\"int\":1}"

<o>
<name type="string">json</name>
<bool type="boolean">true</bool>
<int type="number">1</int>
</o>


instead of:


<o>
<bool type="boolean">true</bool>
<int type="number">1</int>
<name type="string">json</name>
</o>

0
  Sri97's Photo
Posted Jun 18 2012 03:28 AM

Hi,

I have created a standalone class for convering JSON to XML using the above example. But it throwing some exception for the following attached file.

Exception in thread "main" nu.xom.IllegalNameException: NCNames cannot start with the character 35
at nu.xom.Verifier.throwIllegalNameException(Verifier.java:147)
at nu.xom.Verifier.checkNCName(Verifier.java:126)
at nu.xom.Element._setLocalName(Element.java:832)
at nu.xom.Element.<init>(Element.java:112)
at nu.xom.Element.<init>(Element.java:76)
at net.sf.json.xml.XMLSerializer.newElement(XMLSerializer.java:869)
at net.sf.json.xml.XMLSerializer.processJSONObject(XMLSerializer.java:989)
at net.sf.json.xml.XMLSerializer.processJSONValue(XMLSerializer.java:1040)
at net.sf.json.xml.XMLSerializer.processJSONObject(XMLSerializer.java:990)
at net.sf.json.xml.XMLSerializer.processJSONValue(XMLSerializer.java:1040)
at net.sf.json.xml.XMLSerializer.processJSONObject(XMLSerializer.java:990)
at net.sf.json.xml.XMLSerializer.processJSONValue(XMLSerializer.java:1040)
at net.sf.json.xml.XMLSerializer.processJSONObject(XMLSerializer.java:990)
at net.sf.json.xml.XMLSerializer.processJSONValue(XMLSerializer.java:1040)
at net.sf.json.xml.XMLSerializer.processJSONArray(XMLSerializer.java:906)
at net.sf.json.xml.XMLSerializer.processJSONValue(XMLSerializer.java:1035)
at net.sf.json.xml.XMLSerializer.processJSONObject(XMLSerializer.java:990)
at net.sf.json.xml.XMLSerializer.processJSONValue(XMLSerializer.java:1040)
at net.sf.json.xml.XMLSerializer.processJSONArray(XMLSerializer.java:906)
at net.sf.json.xml.XMLSerializer.processJSONValue(XMLSerializer.java:1035)
at net.sf.json.xml.XMLSerializer.processJSONObject(XMLSerializer.java:990)
at net.sf.json.xml.XMLSerializer.processJSONValue(XMLSerializer.java:1040)
at net.sf.json.xml.XMLSerializer.processJSONArray(XMLSerializer.java:906)
at net.sf.json.xml.XMLSerializer.processJSONValue(XMLSerializer.java:1035)
at net.sf.json.xml.XMLSerializer.processJSONObject(XMLSerializer.java:990)
at net.sf.json.xml.XMLSerializer.processJSONValue(XMLSerializer.java:1040)
at net.sf.json.xml.XMLSerializer.processJSONArray(XMLSerializer.java:906)
at net.sf.json.xml.XMLSerializer.processJSONValue(XMLSerializer.java:1035)
at net.sf.json.xml.XMLSerializer.processJSONObject(XMLSerializer.java:990)
at net.sf.json.xml.XMLSerializer.processJSONValue(XMLSerializer.java:1040)
at net.sf.json.xml.XMLSerializer.processJSONArray(XMLSerializer.java:906)
at net.sf.json.xml.XMLSerializer.processJSONValue(XMLSerializer.java:1035)
at net.sf.json.xml.XMLSerializer.processJSONObject(XMLSerializer.java:990)
at net.sf.json.xml.XMLSerializer.processJSONValue(XMLSerializer.java:1040)
at net.sf.json.xml.XMLSerializer.processJSONArray(XMLSerializer.java:906)
at net.sf.json.xml.XMLSerializer.processJSONValue(XMLSerializer.java:1035)
at net.sf.json.xml.XMLSerializer.processJSONObject(XMLSerializer.java:990)
at net.sf.json.xml.XMLSerializer.write(XMLSerializer.java:605)
at net.sf.json.xml.XMLSerializer.write(XMLSerializer.java:570)
at com.bbc.redbutton.jsonxml.ConvertJSONtoXML.main(ConvertJSONtoXML.java:33)
Attached File  front_page.txt (28.21K)
Number of downloads: 219

I am not sure what exactly casuing problem. Please help on this.

Thanks in advance for you help.
0
  Sri97's Photo
Posted Jun 18 2012 05:26 AM

the JSON file contains an element as number which is causing problem. ie

index :{
"43534534":'dsree',
'test':sample
}

Since XML element should not start with number it is failing. is there any other solution on this API.

Regards
Srinivas
0
  Voodoo14's Photo
Posted Jun 26 2012 04:19 PM

hi, after trying a lot, finally I came that all the librarys you need to run this are:

commons-beanutils-1.8.3-bin.zip
commons-collections-3.2.1-bin.zip
commons-io-2.4-bin.zip
commons-lang-2.6-bin.zip (this version, the last doesnt have something, I dont remeber what...)
commons-logging-1.1.1-bin.zip
ezmorph-1.0.6.jar
json-lib-2.4-jdk15.jar
swingx-all-1.6.3.jar
xom-1.2.8.jar

I hope it helps somebody