Saturday 11 May 2013

How to convert JSON object to XML and XML to JSON object?

Conversion of JSON object to XML and XML to JSON object

In the earlier post, I explained how to convert POJO to XML and XML to POJO with JAXB and also provided demonstration for how to convert POJO to JSON and JSON to POJO?

Now with this post, I will explain how to convert JSON object to XML instance document and XML instance document to JSON object?



Example:- JSON to XML and XML to JSON object conversion

In this example, I am retrieving the data from a DB table and generating the retrieved table data in multiple formats for showing the conversion, and for JSON2XML conversion I am passing XML data for conversion into JSON format and then reading the JSON data and converting back to XML object.

System Requirement for this sample application:-
  • JDK 1.6 or above.
  • Eclipse Helios or above
  • Hibernate API jars
  • MySQL database and corresponding jar.

For Table structure, Insert Scripts and Steps to create this demo example
Please follow the below given link:-

Required Jars are:- 


antlr-2.7.6.jar
asm-2.2.2.jar
asm-commons-2.2.2.jar
cglib-nodep-2.1_3.jar
commons-collections.jar
commons-logging.jar
dom4j-1.6.1.jar
ehcache-1.1.jar
hibernate3.jar
jta.jar
log4j-1.2.14.jar
mysql-connector-java-5.0.4-bin.jar

jackson-all-1.8.3.jar.

commons-beanutils-1.7.0.jar
commons-io-1.2.jar
commons-lang-2.0.jar
ezmorph-0.8.1.jar
json-lib-2.2.2-jdk15.jar
jsr311-api-1.1.jar
staxon-0.9.4.jar
xom-1.2.9.jar
  

Only change is in the Converter.java class file.
Converter.java
 
package com.gaurav.conversion.jaxbimplementation;

import java.io.IOException;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.stream.FactoryConfigurationError;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLEventWriter;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;

import net.sf.json.JSON;
import net.sf.json.JSONSerializer;
import net.sf.json.xml.XMLSerializer;

import org.apache.commons.io.IOUtils;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

import de.odysseus.staxon.json.JsonXMLConfig;
import de.odysseus.staxon.json.JsonXMLConfigBuilder;
import de.odysseus.staxon.json.JsonXMLInputFactory;
import de.odysseus.staxon.xml.util.PrettyXMLEventWriter;

public class Converter {

    private static EmpDS employeeDS = new EmpDS();

    private String pojo2Json(Object obj) throws JAXBException,
            JsonParseException, JsonMappingException, IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonString = objectMapper.writeValueAsString(obj);
        return jsonString;
    }

    private Object json2Pojo(String jsonString) throws JAXBException,
            JsonParseException, JsonMappingException, IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        Employees empBeanList = objectMapper.readValue(jsonString,
                Employees.class);
        Object object = (Object) empBeanList;
        return object;
    }

    private String pojo2Xml(Object object, JAXBContext context)
            throws JAXBException {
        Marshaller marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        StringWriter writer = new StringWriter();
        marshaller.marshal(object, writer);
        String xmlStringData = writer.toString();
        return xmlStringData;
    }

    private Employees xml2Pojo(String xmlStringData, JAXBContext context)
            throws JAXBException {
        StringReader reader = new StringReader(xmlStringData);
        Unmarshaller unmarshaller = context.createUnmarshaller();
        Employees employee = (Employees) unmarshaller.unmarshal(reader);
        return employee;
    }

    @SuppressWarnings("deprecation")
    public String XMLtoJSON(String xmlData) {

        String xmlDataForConvertion = null;
        String stringJSONData = null;
        try {

            xmlDataForConvertion = IOUtils.toString(xmlData.getBytes());
            XMLSerializer xmlSerializer = new XMLSerializer();
            JSON json = xmlSerializer.read(xmlDataForConvertion);
            stringJSONData = json.toString(2);

        } catch (Exception e) {

            Logger.getLogger(JsonParseException.class.getName()).log(
                    Level.SEVERE, null, e);
        }

        return stringJSONData;

    }


    public String JSON2XML_FirstApproach(String xmlStringData)
            throws XMLStreamException, FactoryConfigurationError {
        StringWriter strWriter = new StringWriter();
        JsonXMLConfig jsonXMLConfig = new JsonXMLConfigBuilder()
                .multiplePI(false).prettyPrint(false).build();
        // We can also read the XML string data from file
        /**
         * XMLEventReader xmlEventReader = new
         * JsonXMLInputFactory(jsonXMLConfig)
         * .createXMLEventReader(getClass().getClassLoader
         * ().getResourceAsStream(fileName));
         */
        InputStream inputStream = new ByteArrayInputStream(
                xmlStringData.getBytes());
        XMLEventReader xmlEventReader = new JsonXMLInputFactory(jsonXMLConfig)
                .createXMLEventReader(inputStream);
        XMLEventWriter xmlEventWriter = XMLOutputFactory.newInstance()
                .createXMLEventWriter(strWriter);
        xmlEventWriter = new PrettyXMLEventWriter(xmlEventWriter);
        xmlEventWriter.add(xmlEventReader);
        String jsonData = strWriter.getBuffer().toString();
        return jsonData;
    }


    public String JSON2XML_SecondApproach(String xmlStringData)
            throws IOException {

        InputStream inputStream = new ByteArrayInputStream(
                xmlStringData.getBytes());

        String jsonStringData = IOUtils.toString(inputStream);

        XMLSerializer xmlSerializer = new XMLSerializer();
        JSON jsonObject = JSONSerializer.toJSON(jsonStringData);
        xmlSerializer.setRootName("employees");
        xmlSerializer.setTypeHintsEnabled(false);

        String xmlData = xmlSerializer.write(jsonObject);
        return xmlData;
    }


    @SuppressWarnings("unchecked")
    public static void main(String args[]) {

        JAXBContext context = null;

        Converter converter = new Converter();

        List<Employee> employeesList = employeeDS.retrieveEmployee();

        Employee empBean = null;

        Employees employees = new Employees();

        try {
            int counter = 0;
            for (Employee bean : employeesList) {
                empBean = new Employee();
                empBean.setId(bean.getId());
                empBean.setName(bean.getName());
                empBean.setEmail(bean.getEmail());
                counter++;

                employees.setRecCount(counter);
                employees.getEmployee().add(empBean);

            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        String jsonData = null;
        try {

            context = JAXBContext.newInstance(Employees.class);
            String xmlStringData = converter.pojo2Xml(employees, context);
            System.out
                    .println("\nPOJO to XML conversion(Marshal) demonstration in Java\n");
            System.out.println(xmlStringData);

            String XML2JSON = converter.XMLtoJSON(xmlStringData);
            System.out
                    .println("\nXML to JSON conversion demonstration in Java\n");
            System.out.println(XML2JSON);

            String xmlDataFromJSON_1 = converter
                    .JSON2XML_FirstApproach(XML2JSON);

            System.out
                    .println("\nJSON to XML conversion demonstration in Java by First approach\n");

            System.out.println(xmlDataFromJSON_1);

            String xmlDataFromJSON_2 = converter
                    .JSON2XML_SecondApproach(XML2JSON);

            System.out
                    .println("\nJSON to XML conversion demonstration in Java by Second approach\n");

            System.out.println(xmlDataFromJSON_2);

            employees = converter.xml2Pojo(xmlStringData, context);
            System.out
                    .println("\nXML to POJO conversion(UnMarshal) demonstration in Java\n");
            System.out.println(employees);

            jsonData = converter.pojo2Json(employees);
            System.out
                    .println("\nPOJO to JSON conversion demonstration in Java using jackson\n");
            System.out.println(jsonData);

            System.out
                    .println("\nJSON to POJO conversion demonstration in Java using jackson\n");

            Object obj = converter.json2Pojo(jsonData);
            employees = (Employees) obj;
            System.out.println(employees);

        } catch (XMLStreamException xmle) {
            Logger.getLogger(XMLStreamException.class.getName()).log(
                    Level.SEVERE, null, xmle);
        } catch (JsonParseException jpe) {
            Logger.getLogger(JsonParseException.class.getName()).log(
                    Level.SEVERE, null, jpe);
        } catch (JsonMappingException e1) {
            e1.printStackTrace();
        } catch (JAXBException e1) {
            e1.printStackTrace();
        } catch (IOException e1) {
            e1.printStackTrace();
        }

    }
}

Result:-

log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
Hibernate: select employee0_.id as id0_, employee0_.name as name0_, employee0_.email as email0_ from employee employee0_

POJO to XML conversion(Marshal) demonstration in Java

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<employees>
    <employee>
        <id>1</id>
        <name>GAURAV</name>
        <email>gaurav@yahoo.co.in</email>
    </employee>
    <employee>
        <id>2</id>
        <name>Aryan</name>
        <email>Aryan@gmail.com</email>
    </employee>
    <employee>
        <id>7</id>
        <name>Madhu</name>
        <email>madhu@sify.com</email>
    </employee>
    <recCount>3</recCount>
</employees>


XML to JSON conversion demonstration in Java

{
  "employee":   [
        {
      "id": "1",
      "name": "GAURAV",
      "email": "gaurav@yahoo.co.in"
    },
        {
      "id": "2",
      "name": "Aryan",
      "email": "Aryan@gmail.com"
    },
        {
      "id": "7",
      "name": "Madhu",
      "email": "madhu@sify.com"
    }
  ],
  "recCount": "3"
}


JSON to XML conversion demonstration in Java by First approach

<?xml version="1.0" encoding="UTF-8"?>
<employee>
    <id>1</id>
    <name>GAURAV</name>
    <email>gaurav@yahoo.co.in</email>
</employee><employee>
    <id>2</id>
    <name>Aryan</name>
    <email>Aryan@gmail.com</email>
</employee><employee>
    <id>7</id>
    <name>Madhu</name>
    <email>madhu@sify.com</email>
</employee><recCount>3</recCount>



JSON to XML conversion demonstration in Java by Second approach

<?xml version="1.0" encoding="UTF-8"?>
<employees><employee><e><email>gaurav@yahoo.co.in</email><id>1</id><name>GAURAV</name></e><e><email>Aryan@gmail.com</email><id>2</id><name>Aryan</name></e><e><email>madhu@sify.com</email><id>7</id><name>Madhu</name></e></employee><recCount>3</recCount></employees>


XML to POJO conversion(UnMarshal) demonstration in Java

RecordCount: 3
employees:
[Employee [id=1, name=GAURAV, email=gaurav@yahoo.co.in], Employee [id=2, name=Aryan, email=Aryan@gmail.com], Employee [id=7, name=Madhu, email=madhu@sify.com]]

POJO to JSON conversion demonstration in Java using jackson

{"employee":[{"email":"gaurav@yahoo.co.in","name":"GAURAV","id":1},{"email":"Aryan@gmail.com","name":"Aryan","id":2},{"email":"madhu@sify.com","name":"Madhu","id":7}],"recCount":3}

JSON to POJO conversion demonstration in Java using jackson

RecordCount: 3
employees:
[Employee [id=1, name=GAURAV, email=gaurav@yahoo.co.in], Employee [id=2, name=Aryan, email=Aryan@gmail.com], Employee [id=7, name=Madhu, email=madhu@sify.com]]

5 comments:

  1. Gaurav,

    I have a need to convert JSON2XML which has arrays and the output should looks like as you explanined in the "JSON to XML conversion demonstration in Java by First approach"

    I have all the jars as you mentioned (staxon too!!) but I am still getting the error saying ": java.lang.NoClassDefFoundError: de/odysseus/staxon/json/JsonXMLConfigBuilder"

    Can you pl. advise??

    ReplyDelete
    Replies
    1. Hi Soujanya,

      NoClassDefFoundError - This error says that the identified class is not available in that jar, so try with the different version of the jar. Might be the jar you are using is not compatible with other jars.

      Delete
  2. Hi Gaurav..Thank you so much for your reply...yes that was the reason and it was resolved

    ReplyDelete
  3. I have a new requirement now..I need to convert a JSON String to XML (not XML String)..is there any direct method to do it?Really appreciate your response.

    Tried to find online,but everywhere I see the methods returning the XML String..

    Also tried to look for XMLString to XML conversion,all of them are looking for the Root element where as my JSON/XML does not have any root element.

    ReplyDelete
    Replies
    1. As per my knowledge, there is no direct conversion, you need to proceed with customized methods.

      Delete