Monday, March 18, 2013

XML serialization and de-serialization in Java

It is sometimes a great issue when one wants to serialize their objects into XML files. We have JAXB(Java Architecture for XML Binding) API which can serialize and also de-serialize the java object. I will introduce frequently used annotation used for XML serialization with example:

1. Annotating XML variables


@XmlRootElement(namespace="className" or name="className")
@XmlType(propOrder={"property", "list"})
public class className{
   private int attribute;
   private String property;
   private String value;
   private List list;

  @XmlAttribute(value="attribute")
  public int getAttribute(){
   return this.attribute;
  }

@XmlElement(value="property")
  public String getProperty(){
   return this.property;
  }
/*
   @XmlValue
   public String getValue(){
   return this.value;
   }
*/

@XmlElementWrapper(name="lists")
@XmlElement(name="list")
public List getList(){
  return this.list;
 }
}

We can define the annotations for extended objects as follows:

@XmlElementRefs({@XmlElementRef(type=extendedClass1.class),@XmlElementRef(type=extendedClass2.class),@XmlElementRef(type=extendedClass3.class)})
public baseClassObject getObject(){
       return this.object;
}
 

2. Serializing Object


JAXBContext context = JAXBContext.newInstance(className.class);
Marshaller m = context.createMarshaller();
//Format the output
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
m.marshal(classNameObject, fileObject); 
// or to just print to the console
m.marshal(classNameObject, System.out);


3. DeSerialising Object

JAXBContext context = JAXBContext.newInstance(className.class);
Unmarshaller m = context.createUnmarshaller();
classNameObject = (className)m.unmarshal(fileObject);




1 comment: