Saturday, 28 February 2015

JAXB Marshalling & Unmarshalling



JAXB  - JAVA Architecture for XML Binding.
JAXB used to convert Java objects to XML file and vice versa.
JAXB provides mechanism or API to convert Java objects to XML file which is known as Marshalling and XML file to JAVA Objects which is known as Unmarshalling.

JAXB is bundled along with JDK1.6 – so we no need to download any additional jars.
Steps to convert Java Objects to XML file.

  • Create a POJO class which represents a XML file
  • Provide annotations to map each filed of XML to Java class attributes
  • Create a JAXBContext, Marshall objects and call the marshal method

·In the first example we are going to look at following annotations.
·         @XmlRootElement – Denotes the root of the XML document
·         @XmlElement – Denotes the element of the XML document
·         @XmlAttribute – Denotes the attribute of root element

Example - 1
Employee.java
package com.sri.model;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Employee {

       private String empId;
       private String empName;
       private double salary;
      
       public Employee(){
             
       }
       public Employee(String empId, String empName, double salary) {
              super();
              this.empId = empId;
              this.empName = empName;
              this.salary = salary;
       }
       @XmlAttribute(name="employeeId")
       public String getEmpId() {
              return empId;
       }
       public void setEmpId(String empId) {
              this.empId = empId;
       }
       @XmlElement
       public String getEmpName() {
              return empName;
       }
       public void setEmpName(String empName) {
              this.empName = empName;
       }
       @XmlElement
       public double getSalary() {
              return salary;
       }
       public void setSalary(double salary) {
              this.salary = salary;
       }
}

Marshalling.java
package com.sri.model;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

public class Marshalling {

  public static void main(String arg[]){
      
    try {
           JAXBContext jAXBContext = JAXBContext.newInstance(Employee.class) ;
           Marshaller marshaller = jAXBContext.createMarshaller();
           marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
           Employee employee = new Employee("872362","Smith",42730.00);
           marshaller.marshal(employee, new FileOutputStream("d:\\employee.xml"));
       } catch (JAXBException e) {
              e.printStackTrace();
       } catch (FileNotFoundException e) {
              e.printStackTrace();
       }
   }
}

Output:
     <?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
             <employee employeeId="872362">
           <empName>Smith</empName>
           <salary>42730.0</salary>
       </employee>


Example - 2
·         @XmlType(propOrder=”list of elements separated by comma”) – Denotes the order in which elements should be appear on XML
·         @XmlElementWrapper(name = "name of the wrapper") – Denotes wrapper element around XML Element.

Employee.java
package com.sri.jaxb;

import java.util.List;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

@XmlRootElement(name="Employee")
@XmlType(propOrder={"empId","empName","salary","previousExperience"})
public class Employee {

       private String empId;
       private double salary;
       private String empName;
      
       private List<Experience> previousExperience;

       @XmlElement(name="EmployeeId")
       public String getEmpId() {
              return empId;
       }

       public void setEmpId(String empId) {
              this.empId = empId;
       }

       @XmlElement(name="EmployeeName")
       public String getEmpName() {
              return empName;
       }

       public void setEmpName(String empName) {
              this.empName = empName;
       }
       @XmlElement(name="Salary")
       public double getSalary() {
              return salary;
       }

       public void setSalary(double salary) {
              this.salary = salary;
       }
       @XmlElementWrapper(name="Previous-Experiences")
       @XmlElement(name="Experience")
       public List<Experience> getPreviousExperience() {
              return previousExperience;
       }

       public void setPreviousExperience(List<Experience> previousExperience) {
              this.previousExperience = previousExperience;
       }

       public Employee(String empId, String empName, double salary,
                     List<Experience> previousExperience) {
              super();
              this.empId = empId;
              this.empName = empName;
              this.salary = salary;
              this.previousExperience = previousExperience;
       }
      
       public Employee(){
             
       }
}

Experience.java
package com.sri.jaxb;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement

@XmlRootElement
public class Experience {

       private String companyName;
       private int experienceInMonths;
       private String designation;
      
       public Experience(String companyName, int experienceInMonths,
                     String designation) {
              super();
              this.companyName = companyName;
              this.experienceInMonths = experienceInMonths;
              this.designation = designation;
       }

       public Experience() {
       }
      
       @XmlElement(name="CompanyName")
       public String getCompanyName() {
              return companyName;
       }

       public void setCompanyName(String companyName) {
              this.companyName = companyName;
       }
      
       @XmlElement(name="ExperienceInMonths")
       public int getExperienceInMonths() {
              return experienceInMonths;
       }

       public void setExperienceInMonths(int experienceInMonths) {
              this.experienceInMonths = experienceInMonths;
       }
      
       @XmlElement(name="Designation")
       public String getDesignation() {
              return designation;
       }

       public void setDesignation(String designation) {
              this.designation = designation;
       }
}

Marshalling.java
package com.sri.jaxb;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.ArrayList;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

public class Marshalling {

       public static void main(String arg[]){
             
              try {
              JAXBContext jAXBContext = JAXBContext.newInstance(Employee.class) ;
              Marshaller marshaller = jAXBContext.createMarshaller();
              marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
                    
              ArrayList<Experience> experienceList = new ArrayList<Experience>();
              experienceList.add(new Experience("Solution Minds",24,"Junior Engineer"));
              experienceList.add(new Experience("Info Systems",30,"Developer"));
              experienceList.add(new Experience("Mind Bug",24,"Senior Developer"));
              Employee employee = new Employee("872362","Smith",42730.00,experienceList);
              marshaller.marshal(employee, new FileOutputStream("d:\\employee.xml"));
              } catch (JAXBException e) {
                     e.printStackTrace();
              } catch (FileNotFoundException e) {
                     e.printStackTrace();
              }
       }
}

Output:
 <?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
   - <Employee>
               <EmployeeId>872362</EmployeeId>
                 <EmployeeName>Smith</EmployeeName>
                 <Salary>42730.0</Salary>
       <Previous-Experiences>
         <Experience>
                           <CompanyName>Solution Minds</CompanyName>
                           <Designation>Junior Engineer</Designation>
                          <ExperienceInMonths>24</ExperienceInMonths>
                 </Experience>
         <Experience>
                          <CompanyName>Info Systems</CompanyName>
                         <Designation>Developer</Designation>
                         <ExperienceInMonths>30</ExperienceInMonths>
                </Experience>
        <Experience>
                           <CompanyName>Mind Bug</CompanyName>
                          <Designation>Senior Developer</Designation>
                          <ExperienceInMonths>24</ExperienceInMonths>
               </Experience>
           </Previous-Experiences>
  </Employee>

Now we can try unmarshalling.

Unmarshalling.java

package com.sri.jaxb;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Iterator;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

public class Unmarshalling {

  public static void main(String args[]){
     try {
       JAXBContext jAXBContext = JAXBContext.newInstance(Employee.class);
         Unmarshaller unmarshaller = jAXBContext.createUnmarshaller();
         Employee employee = (Employee) unmarshaller.unmarshal
                        (new FileInputStream("d:\\employee1.xm"));
         System.out.println("Employee Name   : "+employee.getEmpName());
         System.out.println("Employee Id     : "+employee.getEmpId());
         System.out.println("Employee Salary : "+employee.getSalary());
         Iterator<Experience> experiences = employee
                                        .getPreviousExperience().iterator();
         while(experiences.hasNext()){
            Experience experience = experiences.next();
            System.out.println("Company Name   : "+experience.getCompanyName());
            System.out.println("Designation    : "+experience.getDesignation());
            System.out.println("Experience     : "+experience
                              .getExperienceInMonths()+" Months");
          }
              } catch (JAXBException e) {
                     e.printStackTrace();
              } catch (FileNotFoundException e) {
                     e.printStackTrace();
              }
       }
}

Output:
Employee Name   : Smith
Employee Id     : 872362
Employee Salary : 42730.0
Company Name   : Solution Minds
Designation    : Junior Engineer
Experience     : 24 Months
Company Name   : Info Systems
Designation    : Developer
Experience     : 30 Months
Company Name   : Mind Bug
Designation    : Senior Developer
Experience     : 24 Months


No comments:

Post a Comment