XStream – Json to Java

XStream can also be used with JSON. XStream provides two drivers : a JsonHierarchicalStreamDriver and a JettisonMappedXmlDriver. The JsonHierarchicalStreamDriver can be used to write a JSON string but cannot deserialize a JSON. JettisonMappedXmlDriver can be used to deserialize a JSON but it introduces an additional dependency. In this example we deserialize a json string into a java object.

Note: The mapping from Java to JSON (and back) is limited, since not anything can be expressed in JSON as with XML. It works quite well for simple objects, but one should not expect wonders. Additionally XStream supports only Jettison 1.0.1. Any other version will not work correctly (even newer ones).

package com.studytrails.xml.xstream;

import java.util.ArrayList;
import java.util.List;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamImplicit;
import com.thoughtworks.xstream.io.json.JettisonMappedXmlDriver;

public class XStreamJsonExample {

	private String json = "{Music:{albums:[{name:name1,year:1980}]}}";

	public static void main(String[] args) {
		XStreamJsonExample example = new XStreamJsonExample();

	private void serializeJsonUsingxStream() {

		XStream xStream = new XStream(new JettisonMappedXmlDriver());
		Music7 music7 = (Music7) xStream.fromXML(json);
		Music7 music = new Music7();
		Album7 album1 = new Album7();
		album1.name = "name1";
		album1.year = 1980;
		Album7 album2 = new Album7();
		album2.name = "name2";
		album2.year = 1981;

class Music7 {
	List<Album7> albums = new ArrayList<Album7>();

	public String toString() {
		return "Music7 [albums=" + albums + "]";


class Album7 {
	String name;
	int year;

	public String toString() {
		return "Album7 [name=" + name + ", year=" + year + "]";

Leave a Comment