Due to XStream's flexible architecture, handling of JSON mappings is as easy as handling of XML documents. All you have to do is to initialize XStream object with an appropriate driver and you are ready to serialize your objects to (and from) JSON.
XStream currently delivers two drivers for JSON: The JsonHierarchicalStreamDriver and the JettisonMappedXmlDriver. The first one does not have an additional dependency, but can only be used to write XML, while the second one is based on Jettison and can also deserialize JSON to Java objects again.
Jettison driver uses Jettison StAX parser to read and write data in JSON format. It is available in XStream from version 1.2.2 and is implemented in com.thoughtworks.xstream.io.json.JettisonMappedXmlDriver
class.To successfully use this driver you need to have Jettison project and StAX API in your classpath.
The following Maven configuration snippet should get all necessary JARs for you.
<dependency> <groupId>com.thoughtworks.xstream</groupId> <version>1.2.2</version> <artifactId>xstream</artifactId> </dependency> <dependency> <groupId>org.codehaus.jettison</groupId> <artifactId>jettison</artifactId> <version>1.0-RC1</version> </dependency> <dependency> <groupId>stax</groupId> <artifactId>stax-api</artifactId> <version>1.0.1</version> </dependency>
Alternatively you can download JARs manually.
Here are a few simple examples:
The following example:
package org.sensatic.json.test; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.io.json.JettisonMappedXmlDriver; public class WriteTest { public static void main(String[] args) { Product product = new Product("Banana", "123", 23.00); XStream xstream = new XStream(new JettisonMappedXmlDriver()); xstream.alias("product", Product.class); System.out.println(xstream.toXML(product)); } }
produces the following JSON document:
{"product":{"name":"Banana","id":"123","price":"23.0"}}
As you can see, all standard XStream features (such as aliases) can be used with this driver.
The following code:
package org.sensatic.json.test; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.io.json.JettisonMappedXmlDriver; public class ReadTest { public static void main(String[] args) { String json = "{\"product\":{\"name\":\"Banana\",\"id\":\"123\"" + ",\"price\":\"23.0\"}}"; XStream xstream = new XStream(new JettisonMappedXmlDriver()); xstream.alias("product", Product.class); Product product = (Product)xstream.fromXML(json); System.out.println(product.getName()); } }
serializes JSON document created with preceding example back to Java object. It prints:
Banana
as a result.