About Anirudh Bhatnagar

Anirudh is a Java programmer with extensive experience in building Java/J2EE applications. He has always been fascinated by the new technologies and emerging trends in software development. He has been involved in propagating these changes and new technologies in his projects. He is an avid blogger and agile enthusiast who believes in writing clean and well tested code.

Converting JSON to XML to Java Objects using XStream

XStream library can be an effective tool for converting JSON to Java to XML translations to and fro.
Lets explore each one of them one by one, and see which driver is used.

Handling JSONs

To convert JSON to Java objects all you have to do is initialize XStream object with an appropriate driver and you are ready to serialise your objects to (and from) JSON.

XStream currently delivers two drivers for JSON to Object ocnversion:
 

  1. JsonHierarchicalStreamDriver: This does not have an additional dependency, but can only be used to write XML
  2. JettisonMappedXmlDriver: This is based on Jettison and can also deserialize JSON to Java objects again.

Jettison driver

Jettison driver uses Jettison StAX parser to read and write data in JSON format. It is available in XStream since version 1.2.2 and is implemented in com.thoughtworks.xstream.io.json.JettisonMappedXmlDriver class.

In order to get this working, we need to add the dependencies in pom :

<dependencies>
        <dependency>
            <groupId>com.thoughtworks.xstream</groupId>
            <artifactId>xstream</artifactId>
            <version>1.4.7</version>
        </dependency>
        <dependency>
            <groupId>org.codehaus.jettison</groupId>
            <artifactId>jettison</artifactId>
            <version>1.1</version>
        </dependency>
    </dependencies>

And the code to convert JSON to object and object to Json :

XStream xstream = new XStream(new JettisonMappedXmlDriver());
xstream.toXML(xml);  //converts Object to JSON
xstream.fromXML(obj); //Converts Json to Object

Serializing an object to XML

To serialize an Object to XML XStream uses 2 drivers :

  1. StaxDriver
  2. XStream xstream = new XStream(new StaxDriver());
    xstream.toXML(xml);  //converts Object to XML
    xstream.fromXML(obj); //Converts XML to Object

  3. DomDriver
  4. XStream xstream = new XStream(new DomDriver());
    xstream.toXML(xml);  //converts Object to XML
    xstream.fromXML(obj); //Converts XML to Object

Finally, lets see all these in one class:

package com.anirudh;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.json.JettisonMappedXmlDriver;
import com.thoughtworks.xstream.io.xml.DomDriver;
import com.thoughtworks.xstream.io.xml.StaxDriver;

/**
 * Created by anirudh on 15/07/14.
 */
public class Transformer<T> {

    private static final XStream XSTREAM_INSTANCE = null;

    public T getObjectFromJSON(String json){
        return (T) getInstance().fromXML(json);
    }

    public String getJSONFromObject(T t){
        return getInstance().toXML(t);
    }

    private XStream getInstance(){
        if(XSTREAM_INSTANCE==null){
            return new XStream(new JettisonMappedXmlDriver());
        }  else {
            return XSTREAM_INSTANCE;
        }
    }

    public T getObjectFromXML(String xml){
        return (T)getStaxDriverInstance().fromXML(xml);
    }

    public String getXMLFromObject(T t){
        return getStaxDriverInstance().toXML(t);
    }

    public T getObjectFromXMLUsingDomDriver(String xml){
        return (T)getDomDriverInstance().fromXML(xml);
    }

    public String getXMLFromObjectUsingDomDriver(T t){
        return getDomDriverInstance().toXML(t);
    }

    private XStream getStaxDriverInstance(){
        if(XSTREAM_INSTANCE==null) {
            return new XStream(new StaxDriver());
        }else{
            return XSTREAM_INSTANCE;
        }
    }

    private XStream getDomDriverInstance(){
        if(XSTREAM_INSTANCE==null){
            return new XStream(new DomDriver());
        }else{
            return XSTREAM_INSTANCE;
        }
    }
}

Write a JUnit class to test it:

package com.anirudh;

import com.anirudh.domain.Product;
import org.junit.Before;
import org.junit.Test;

/**
 * Created by anirudh on 15/07/14.
 */
public class TransformerTest {

    private Transformer<Product> productTransformer;
    private Product product;
    @Before
    public void init(){
        productTransformer = new Transformer<Product>();
        product = new Product(123,"Banana",23.00);
    }
    @Test
    public void testJSONToObject(){
        String json = productTransformer.getJSONFromObject(product);
        System.out.println(json);
        Product convertedproduct = productTransformer.getObjectFromJSON(json);
        System.out.println(convertedproduct.getName());
    }

    @Test
    public void testXMLtoObjectForStax(){
        String xml = productTransformer.getXMLFromObject(product);
        System.out.println(xml);
        Product convertedproduct = productTransformer.getObjectFromXML(xml);
        System.out.println(convertedproduct.getName());
    }

    @Test
    public void testXMLtoObjectForDom(){
        String xml = productTransformer.getXMLFromObjectUsingDomDriver(product);
        System.out.println(xml);
        Product convertedproduct = productTransformer.getObjectFromXMLUsingDomDriver(xml);
        System.out.println(convertedproduct.getName());
    }

}

The full code can be seen here.
In the next blog, we will compare the use cases, exploring where what fits in.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.

Leave a Reply


1 × five =



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close