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

Cover of 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.

Learn More Read Now on Safari


Tags:
1 Subscribe


2 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"]}