Enterprise Integration Zone is brought to you in partnership with:

Bosanac Dejan is a Senior Software Engineer at FuseSource specializing in messaging and integration with Apache ActiveMQ Dejan is a DZone MVB and is not an employee of DZone and has posted 16 posts at DZone. You can read more from them at their website. View Full User Profile

A Crazy Fast Way to Convert XML to JSON

09.19.2012
| 9950 views |
  • submit to reddit

While working on Jettison, I often need to convert XML to JSON. Here’s a simple method that uses XStream and Jettison:

import java.io.StringReader;
import java.io.StringWriter;

import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.copy.HierarchicalStreamCopier;
import com.thoughtworks.xstream.io.json.JettisonMappedXmlDriver;
import com.thoughtworks.xstream.io.xml.XppReader;

public class Test {

	public static void main(String[] args) throws Exception {

		String xml = "ToveJaniReminder" +
				"Don't forget me this weekend!";

        HierarchicalStreamReader sourceReader = new XppReader(new StringReader(xml));

        StringWriter buffer = new StringWriter();
        JettisonMappedXmlDriver jettisonDriver = new JettisonMappedXmlDriver();
        jettisonDriver.createWriter(buffer);
        HierarchicalStreamWriter destinationWriter = jettisonDriver.createWriter(buffer);

        HierarchicalStreamCopier copier = new HierarchicalStreamCopier();
        copier.copy(sourceReader, destinationWriter);

        System.out.println(buffer.toString());
	}

}

All conversion problems like lists representation are handled by Jetttison. This example uses Mapped convention, but of course, BadgerFish notation can be used as well.

 

Published at DZone with permission of Dejan Bosanac, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)