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.

Related Whitepaper:

Bulletproof Java Code: A Practical Strategy for Developing Functional, Reliable, and Secure Java Code

Use Java? If you do, you know that Java software can be used to drive application logic of Web services or Web applications. Perhaps you use it for desktop applications? Or, embedded devices? Whatever your use of Java code, functional errors are the enemy!

To combat this enemy, your team might already perform functional testing. Even so, you're taking significant risks if you have not yet implemented a comprehensive team-wide quality management strategy. Such a strategy alleviates reliability, security, and performance problems to ensure that your code is free of functionality errors.Read this article to learn about this simple four-step strategy that is proven to make Java code more reliable, more secure, and easier to maintain.

Get it Now!  

Leave a Reply


one + = 10



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
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.

Sign up for our Newsletter

20,709 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books