Sunday 9 October 2011

Marshalling vs UnMarshalling

Marshalling: The process of converting java object into xml instance 


Unmarsalling: The process of converting XML instance into java objects




Marshal Java object to xml file :-



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

public class ObjectToXml {
  public static void main(String[] argsthrows Exception {
    JAXBContext contextObj JAXBContext.newInstance(Employee.class);

    Marshaller marshallerObj contextObj.createMarshaller();
    marshallerObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUTtrue);

    Student myStudent = new Student();
    myStudent.set
Gender("M");
    myStudent.setName("Amar");
    myStudent.setAge(20);
    marshallerObj .marshal(object, new FileOutputStream("Student.xml")); 
  }


UnMarshal xml file to Java object :-

import java.io.FileOutputStream;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;

public class XmlToObject {
  public static void main(String[] argsthrows Exception {
    JAXBContext jc = JAXBContext.newInstance ();

    Unmarshaller u = jc.createUnmarshaller ();  
      
    File f = new File ("Student.xml");
    JAXBElement element = (JAXBElement) u.unmarshal (f);

    Student myStudent = (Student) element.getValue ();
    System.out.println (myStudent.getGender ());
    System.out.println (myStudent.getName ());
    System.out.println (myStudent.getAge ());
  }




import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
class Student{
  private String gender;

  private String name;

  private int age;

  public String getGender() {
    return gender;
  }

  public void setGender(String gender) {
    this.gendergender;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name name;
  }

  public int getAge() {
    return age;
  }

  public void setAge(int age) {
    this.ageage;
  }



Student.xml



<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<student>
    <gender>M</gender>
    <name>Amar</name>
    <age>20</age>
</student>

Serialization: The process of converting java object into byte stream.

Deserialization: The process of converting the byte stream into java object.