Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

A Crazy Fast Way to Convert XML to JSON

DZone's Guide to

A Crazy Fast Way to Convert XML to JSON

· Integration Zone
Free Resource

Modernize your application architectures with microservices and APIs with best practices from this free virtual summit series. Brought to you in partnership with CA Technologies.

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.

 

The Integration Zone is proudly sponsored by CA Technologies. Learn from expert microservices and API presentations at the Modernizing Application Architectures Virtual Summit Series.

Topics:

Published at DZone with permission of Dejan Bosanac, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}