Core Java

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.

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.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Piyush Chordia
9 years ago

If you have a valid dtd file for your XML, then you can easily transform json to xml and xml to json using the eclipselink jar binary.

Refer this: http://www.cubicrace.com/2015/06/How-to-convert-XML-to-JSON-format.html

Back to top button