bind

JAXB Binding Example

JAXB stands for Java Architecture for XML Binding. JAXB provides convenient way to bind XML schemas and Java representations, making it easy for developers to work with XML data and its processing in Java based applications. To help with this, JAXB provides methods for unmarshalling XML instance documents into Java content trees, and then marshalling Java content trees back into XML instance documents. JAXB also provides a way to generate XML schema from Java objects.

1. What is JAXB?

XML and Java are helping developers in exchange of data and programs across the Internet. This is because XML has emerged as the standard for exchanging data across disparate systems, and Java technology provides a platform for building portable applications. This is particularly important for Web services.

One way to achieve this is using the most common XML parsers like DOM or SAX but that led to somehow clumsy code.

The other way is using JAXB which makes this task very easy.

2. Marshal the document

To understand how to marshal the document, let’s create two POJO classes, Person and Address. At design level, Person has Address.

Address.java

package com.javacodegeeks.examples.entities;

import javax.xml.bind.annotation.XmlType;

@XmlType
public class Address {
	private String addressLine1;
	private String addressLine2;
	private String state;
	private String country;
	private int zip;

	public Address(String addressLine1, String addressLine2, String state, String country, int zip) {
		super();
		this.addressLine1 = addressLine1;
		this.addressLine2 = addressLine2;
		this.state = state;
		this.country = country;
		this.zip = zip;
	}

	public Address() {
		super();
	}
	public String getAddressLine1() {
		return addressLine1;
	}

	public void setAddressLine1(String addressLine1) {
		this.addressLine1 = addressLine1;
	}

	public String getAddressLine2() {
		return addressLine2;
	}

	public void setAddressLine2(String addressLine2) {
		this.addressLine2 = addressLine2;
	}

	public String getState() {
		return state;
	}

	public void setState(String state) {
		this.state = state;
	}

	public String getCountry() {
		return country;
	}

	public void setCountry(String country) {
		this.country = country;
	}

	public int getZip() {
		return zip;
	}

	public void setZip(int zip) {
		this.zip = zip;
	}
	
	@Override
	public String toString() {
		return "addressLine1: " + addressLine1 + ", addressLine2: " + addressLine2 + 
				", state: " + state + ", country: " + country + 
				", zip: " + zip;
	}
}

Person.java

package com.javacodegeeks.examples.entities;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Person {
	private int id;
	private String name;
	private Address address;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

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

	public Address getAddress() {
		return address;
	}

	public void setAddress(Address address) {
		this.address = address;
	}

	public Person(int id, String name, Address address) {
		super();
		this.id = id;
		this.name = name;
		this.address = address;
	}

	public Person() {
		super();
	}

	@Override
	public String toString() {
		return "id: " + id + ", name: " + name + ", address: " + address;
	}
}

Notice that Address class has been annotated with @XmlType and Person class has been annotated with @XmlRootElement. These annotations direct the marshaling of Person object, where marshaling is the process of encoding an in-memory object to an XML document. This XML document can be sent across network to be unmarshaled and decoded at other end.
Annotation @XmlType implies that JAX-B should generate XML schema type from the corresponding Java type. @XmlRootElement implies that JAX-B should generate outermost or root element XML schema from the corresponding Java class.

Now let’s look at a program to marshal Person class.

MarshalPerson.java

package com.javacodegeeks.examples.jaxb;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

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

import com.javacodegeeks.examples.entities.Address;
import com.javacodegeeks.examples.entities.Person;

public class MarshalPerson {
	public static void main(String[] args) throws JAXBException, FileNotFoundException {
		new MarshalPerson().runMarshalExample();
	}
	
	private Person createPerson() {
		Address address = new Address("addressLine1", "addressLine2", "state", "country", 11582);
		Person person = new Person(1, "name", address);
		return person;
	}
	
	private void runMarshalExample() throws JAXBException, FileNotFoundException {
		Person person = createPerson();
		
		JAXBContext context = JAXBContext.newInstance(Person.class);
		Marshaller marshaller = context.createMarshaller();
		marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
		
		FileOutputStream fileOutputStream = new FileOutputStream(new File("person.xml"));
		
		marshaller.marshal(person, fileOutputStream);
	}
}

On executing the above program, person.xml file shall get generated in project’s root directory. This content of this file can be wired over network in byte stream.

person.xml

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<person>
    <address>
        <addressLine1>addressLine1</addressLine1>
        <addressLine2>addressLine2</addressLine2>
        <country>country</country>
        <state>state</state>
        <zip>11582</zip>
    </address>
    <id>1</id>
    <name>name</name>
</person>

By default, JAX-B marshaling follows standard Java and JavaBean naming conventions, however, with bunch of JAX-B annotations, it can be overridden if required.

3. Unmarshal the document

In this section we shall see the reverse of marshaling process. We shall be unmarshaling person.xml generated in previous section in order to generate Person object.

UnmarshalPerson.java

package com.javacodegeeks.examples.jaxb;

import java.io.File;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

import com.javacodegeeks.examples.entities.Person;

public class UnmarshalPerson {
	public static void main(String[] args) throws JAXBException {
		new UnmarshalPerson().runExample();
	}

	private void runExample() throws JAXBException {
		JAXBContext context = JAXBContext.newInstance(Person.class);
		Unmarshaller unmarshaller = context.createUnmarshaller();
		
		Person person = (Person) unmarshaller.unmarshal(new File("person.xml"));
		
		System.out.println(person);
		
	}
}

The output of this program shall be:

id: 1, name: name, address: addressLine1: addressLine1, addressLine2: addressLine2, state: state, country: country, zip: 11582

Here we can see that the xml has now been decoded back into Person object.

4. Download the source code

This was an example of JAXB Binding.

Download
You can download the full source code of this example here: JAXBBindingExample

Saurabh Arora

Saurabh graduated with an engineering degree in Information Technology from YMCA Institute of Engineering, India. He is SCJP, OCWCD certified and currently working as Technical Lead with one of the biggest service based firms and is involved in projects extensively using Java and JEE technologies. He has worked in E-Commerce, Banking and Telecom domain.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button