Sunday, 5 August 2012

JAXB XML Marshalling / Unmarshalling

We are going to perform a simple round trip to convert an JAXB annotated Java object into an XML (marshalling) and back into an XML object (unmarshalling). The code example is available on GitHub in the JAXB-JSON-XML Marshalling directory.

The following is a simple Java object with JAXB annotation:
public class Book {

    private String title;
    private int year;

    public String getTitle() {
        return title;

    public void setTitle(String title) {
        this.title = title;

    public int getYear() {
        return year;

    public void setYear(int year) {
        this.year = year;

The following code performs the round trip:
    public static void main(String[] args) throws JAXBException {

        Book book = new Book();
        book.setTitle("Book title");

        // Creating a Marshaller
        JAXBContext jaxbContext = JAXBContext.newInstance(Book.class);
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        StringWriter result = new StringWriter();
        jaxbMarshaller.marshal(book, result);

        // Printing XML
        String xml = result.toString();

        // Creating an Unmarshaller
        Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
        StringReader sr = new StringReader(xml);
        Book retr = (Book) jaxbUnmarshaller.unmarshal(sr);
        System.out.println("Title: " + retr.getTitle());
        System.out.println("Year : " + retr.getYear());

The output is:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <title>Book title</title>

Title: Book title
Year : 2010

Pojo to XMLPojo to JSONJAXB to XMLJAXB to JSONJAXB Annotations Tutorial Table Of Content