JAXB Marshalling UnMarshalling using Generics


JAXB, stands for Java Architecture for XML Binding, using JAXB annotation to convert Java object to / from XML file. In this tutorial, we show you how to use JAXB to do following stuffs:
  1. Marshalling – Convert a Java object into a XML file.
  2. Unmarshalling – Convert XML content into a Java Object.
Technologies used in this article:
  1. JDK 1.6
  2. JAXB 2.0
Working with JAXB is easy, just annotate object with JAXB annotation, later use jaxbMarshaller.marshal() or jaxbMarshaller.unmarshal() to do the object / XML conversion.

JAXB Dependency

No extra jaxb libraries are required if you are using JDK1.6 or above, because JAXB is bundled in JDK 1.6.

Note:

For JDK < 1.6, download JAXB from here, and puts “jaxb-api.jar” and “jaxb-impl.jar” on your project classpath.

JAXB Annotation

For object that need to convert to / from XML file, it have to annotate with JAXB annotation. The annotation are pretty self-explanatory, you can refer to this JAXB guide for detail explanation.
Sample XML:


<student>
    <marks>99.99</marks>
    <name>Name</name>
    <rank>1</rank>
    <rollno>12</rollno>
</student>


POJO Class:


package jaxbutil;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name="student")
public class Student {
    private String name;
    private int rollNo;
    private double marks;
    private int rank;

    public double getMarks() {
        return marks;
    }
    public void setMarks(double marks) {
        this.marks = marks;
    }
    public int getRank() {
        return rank;
    }
    public void setRank(int rank) {
        this.rank = rank;
    }
    public int getRollNo() {
        return rollNo;
    }
    public void setRollNo(int rollNo) {
        this.rollNo = rollNo;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}


Convert Object to XML:

JAXB marshalling example, convert Student object into a XML file. The jaxbMarshaller.marshal() contains a lot of overloaded methods, find one that suit your output.

public static String convertObjectToXML(Student object) {
        try {
            StringWriter stringWriter = new StringWriter();
            JAXBContext context = JAXBContext.newInstance(object.getClass());
            Marshaller marshaller = context.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            marshaller.marshal(object, stringWriter);
            return stringWriter.toString();
        } catch (JAXBException e) {
            System.err.println(String.format("Exception while marshalling: %s", e.getMessage()));
        }
        return null;
    }

 public static void main(String args[]){
         

        Student student = new Student();
        student.setMarks(123);
        student.setName("CODESUGGESTIONS");
        student.setRank(2);
        student.setRollNo(123);
        String studentXML = convertObjectToXML(student);
        System.out.println(studentXML);

    }

Here is the Output:


<student>
    <marks>123.0</marks>
    <name>CODESUGGESTIONS</name>
    <rank>2</rank>
    <rollno>123</rollno>
</student>


The above JAXB Conversion method Parameter type is Student type. Suppose if we want to convert Order object then we need to write another method.
So the above method we can write using Generics in the following way.

public static  String convertObjectToXML(T object) {
        try {
            StringWriter stringWriter = new StringWriter();
            JAXBContext context = JAXBContext.newInstance(object.getClass());
            Marshaller marshaller = context.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            marshaller.marshal(object, stringWriter);
            return stringWriter.toString();
        } catch (JAXBException e) {
            System.err.println(String.format("Exception while marshalling: %s", e.getMessage()));
        }
        return null;
    }

public static void main(String args[]){ 
        Student student = new Student();
        student.setMarks(123);
        student.setName("CODESUGGESTIONS");
        student.setRank(2);
        student.setRollNo(123);
        String studentXML = convertObjectToXML(student);
        System.out.println(studentXML);

    }


Here is the Output:


<student>
    <marks>123.0</marks>
    <name>CODESUGGESTIONS</name>
    <rank>2</rank>
    <rollno>123</rollno>
</student>


Suppose if we want to convert then we need to Pass Order Object.

Convert XML to Object

JAXB unmarshalling example, convert a XML file content into a Student object. The jaxbMarshaller.unmarshal() contains a lot of overloaded methods, find one that suit yours.

public static Student convertXMLToObject(String xml) {
        try {
            JAXBContext context = JAXBContext.newInstance(Student.class);
            Unmarshaller um = context.createUnmarshaller();
            Student student = (Student) um.unmarshal(new StringReader(xml));
            return student;
        } catch (JAXBException je) {
            throw new RuntimeException("Error interpreting XML response", je);
        }
    }

In the Above Method the XML content is converted to Student object and it returns the Student object.
Suppose if we want to convert to Customer object then we need to write another method in the following way.

public static Customer convertXMLToObject(String xml) {
        try {
            JAXBContext context = JAXBContext.newInstance(Customer.class);
            Unmarshaller um = context.createUnmarshaller();
            Customer  customer = (Customer) um.unmarshal(new StringReader(xml));
            return student;
        } catch (JAXBException je) {
            throw new RuntimeException("Error interpreting XML response", je);
        }
    }

We can refine this method that will convert any string to Object of any type in the following way.

public static  T convertXMLToObject(Class clazz, String xml) {
        try {
            JAXBContext context = JAXBContext.newInstance(clazz);
            Unmarshaller um = context.createUnmarshaller();
            return (T) um.unmarshal(new StringReader(xml));
        } catch (JAXBException je) {
            throw new RuntimeException("Error interpreting XML response", je);
        }
    }

In the above method it will accept Class type and it will return the generic type object.

No comments

Powered by Blogger.