Showing posts with label JSON. Show all posts
Showing posts with label JSON. Show all posts

Friday, 15 March 2019

A complete example to convert JSON file into Java Objects

JSON to Java Conversion

      Maven Dependency required for this project

<dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-mapper-asl</artifactId>
    <version>1.9.13</version>
</dependency>

<dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.9.6</version>
    </dependency>

Conversion from JSON to JAVA object takes place by following below two steps,


  •        By Creating instance of com.fasterxml.jackson.databind.ObjectMapper
  •        Then using objectMapper.readValue() method to convert JSON to Java object


ObjectMapper mapper = new ObjectMapper();
allQuestions =  mapper.readValue(new File("questions.json"), AllQuestions.class);


Complete Example:

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.gaurav.json</groupId>
<artifactId>jackson-example</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.codehaus.jackson/jackson-mapper-asl -->
<dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-mapper-asl</artifactId>
    <version>1.9.13</version>
</dependency>
 <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.9.6</version>
    </dependency>
</dependencies>
</project>

Java Pojo Classes:

AllQuestions.java


package com.gaurav.jackson.model;
public class AllQuestions
{
    private Questions[] questions;
    public Questions[] getQuestions ()
    {
        return questions;
    }
    public void setQuestions (Questions[] questions)
    {
        this.questions = questions;
    }
    @Override
    public String toString()
    {
        return "AllQuestions [questions = "+questions+"]";    }
}



Questions.java


package com.gaurav.jackson.model;
public class Questions
{
    private String questionIdId;
    private QuestionDetails questionDetails;
    public String getQuestionIdId ()
    {
        return questionIdId;    }
    public void setQuestionIdId (String questionIdId)
    {
        this.questionIdId = questionIdId;
    }
    public QuestionDetails getQuestionDetails ()
    {
        return questionDetails;    }
    public void setQuestionDetails (QuestionDetails questionDetails)
    {
        this.questionDetails = questionDetails;    }
    @Override
    public String toString()
    {
        return "Questions [questionIdId = "+questionIdId+", questionDetails = "+questionDetails+"]";    }
}



QuestionDetails.java


package com.gaurav.jackson.model;
public class QuestionDetails
{
    private String data;
    private String index;
    private String exam_id;
    public String getData ()
    {
        return data;
    }
    public void setData (String data)
    {
        this.data = data;
    }
    public String getIndex ()
    {
        return index;
    }
    public void setIndex (String index)
    {
        this.index = index;
    }
    public String getExam_id ()
    {
        return exam_id;
    }
    public void setExam_id (String exam_id)
    {
        this.exam_id = exam_id;
    }
    @Override
    public String toString()
    {
        return "QuestionDetails [data = "+data+", index = "+index+", exam_id = "+exam_id+"]";    }
}

  • Main Java class which will help to read the JSON file and convert that into Java object.



JSON2JavaConverter.java
package com.gaurav.jackson.json;
import java.io.File;
import java.io.IOException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.gaurav.jackson.model.AllQuestions;
import com.gaurav.jackson.model.QuestionDetails;
import com.gaurav.jackson.model.Questions;
public class JSON2JavaConverter {
public static void main(String[] args) {
  AllQuestions allQuestions = null;
        ObjectMapper mapper = new ObjectMapper();
        try         {
        allQuestions =  mapper.readValue(new File("questions.json"), AllQuestions.class);
        } catch (JsonGenerationException e)
        {
          e.printStackTrace();
        } catch (JsonMappingException e)
        {
          e.printStackTrace();
        } catch (IOException e)
        {
          e.printStackTrace();
        }
            Questions[] quesArray = allQuestions.getQuestions();
        for(Questions question: quesArray) {
        QuestionDetails questionDetails = question.getQuestionDetails();
        System.out.println("questionDetail Exam ID:"+questionDetails.getExam_id());
        System.out.println("questionDetail Index:"+questionDetails.getIndex());
        System.out.println("questionDetail Data:"+questionDetails.getData());
        }
        }
}


OUTPUT:


questionDetail Exam ID:2345190
questionDetail Index:0
questionDetail Data:{"Which of the following was most probably the first metal to be used in India?", "answers": "[A] Iron", "[B] Copper", "[C] Gold"," [D] Silver", " Answer is": "[B] Copper"}
questionDetail Exam ID:2345191
questionDetail Index:1
questionDetail Data:{"Entomology is the science that studies?", "answers": "[A] Behavior of human beings", "[B] Insects", "[C] The origin and history of technical and scientific terms"," [D] The formation of rocks", " Answer is": "[B] Insects"}
questionDetail Exam ID:2345190
questionDetail Index:2
questionDetail Data:{"For galvanizing iron which of the following metals is used?", "answers": "[A] Aluminium", "[B] Copper", "[C] Lead"," [D] Zinc", " Answer is": "[D] Zinc"}

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]]

How to Convert POJO to JSON and JSON to POJO?


Conversion of POJO to JSON and JSON to POJO

In the previous post I explained that how to convert POJO to XML and XML to POJO? Now with this post I am going to explain about how to convert POJO to JSON and JSON to POJO? At first, we will look into what is JSON?

JSON stands for JavaScript Object Notation. 

  • JSON format is a text format and it is completely language independent. 
  • It is having similar feature than XML. 
  • It can also be used for storing and exchanging text information. 
  • JSON format is providing easier and faster way to parse the content. 
  • It is a lightweight text-data interchange format. 
  • As JSON is self-describing format so it is very easy to understand. 
  • JavaScript syntax is used for describing data objects by JSON. 
  • JSON is following a hierarchical structure means it is containing values within values. 
  • The media type for JSON is application/JSON and the file extension used for JSON is .json.   
  • This format (JSON) is also used for serializing and transmitting structured data over a network connection. 
  • It is performing as an alternative to XML.

Douglas Crockford,  An American computer programmer and entrepreneur is the person who has originally specified and popularized the JSON format.

JSON Format sample data:-

{
  "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"
}

Description of above sample:-

About Keys and Values in JSON data format:-
  • Keys and Values are two primary parts that make up JSON data.
  • Key: A key is always a string enclosed in “” (quotation marks).
  • Value: A value can be a string or integer or Boolean or array or an object.
  • Key-Value Pair: It follows a specific syntax. Key is separated with Value by a colon and these pairs are separated by comma with others.

Types of values in JSON format data consists of the below basic elements:
  • Objects: Objects starts and ends with curly braces ({}).
  • Object Members:  Members consist of strings and values, separated by colon (:). Members are separated by commas.
  • Strings: Strings are surrounded by “” (double quotes) and contain Unicode characters or (\) common backslash escapes.
  • Values: A value can be a string or a number or an object or an array or Boolean true or false or null (empty).
  • Arrays:  Arrays starts and ends with braces and contain values. Values are separated by commas.

Example:- POJO to JSON and JSON to POJO conversion

In this example, I am retrieving the data from a DB table and generating the retrieved table data as Java object and converting it as JSON data and then reading the JSON data and converting back it to java object.

System Requirement for this sample application:-
  • The Extra jar needed for the execution of this program is jackson-all-1.8.3.jar.
  • JDK 1.6 or above.
  • Eclipse Helios or above
  • Hibernate API jars
  • MySQL database and corresponding jar.

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

Only change is in the client program file.

Converter.java

package com.gaurav.jaxbimplementation;

import java.io.IOException;

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 org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

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("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");
            System.out.println(xmlStringData);

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

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

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

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

        } 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 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]]