REST XML Example using Jersey 2 and JAXB – RESTful Web Services Tutorial

2 years ago Lalit Bhagtani 0

REST XML Example :- In this tutorial, we will learn to produce XML response using Jersey 2.

JAXB is used to convert java object to XML response. Jersey 2 libraries contains JAXB libraries, so there is no need to add any JAXB related dependency in pom.xml file of your project.

Let’s try to understand it with an example.

Example :-

JAXB Annotation

Create a bean class “Book” with few class members. This class will be used as an entity to send a response to client in XML format. We will annotated our bean class with JAXB annotation to convert it to XML. Some of the JAXB annotation used in the below example are as follows : 

1. @XmlRootElement :- It maps a class or an enum type to an XML element ( root element ).
2. @XmlElement :- It maps a Java Bean property to a XML element.
3. @XmlAttribute :- It maps a Java Bean property to a XML attribute.
4. @XmlTransient :- It prevents the mapping of a Java Bean property to XML representation.

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;

public class Book {

  private String id;
  private String name;
  private String authorName;
  private int volumeNumber;
  private String publisher;
  public String getId() {
    return id;
  public void setId(String id) { = id;
  public String getName() {
    return name;
  public void setName(String name) { = name;
  public String getAuthorName() {
    return authorName;
  public void setAuthorName(String authorName) {
    this.authorName = authorName;
  public int getVolumeNumber() {
    return volumeNumber;
  public void setVolumeNumber(int volumeNumber) {
    this.volumeNumber = volumeNumber;

  public String getPublisher() {
    return publisher;

  public void setPublisher(String publisher) {
    this.publisher = publisher;

Request :-

In this example REST XML Example, we will hit this URL <base URL>/books/1 to get the book resource of id 1. To get a response in XML format, we will annotate the method with @Produces annotation with APPLICATION_XML MIME media type. Jersey library will convert the JAXB annotated java object to XML file automatically.


public class ProducesAnnotationExample {

  public Response getAllBooks(@PathParam("id") String bookId){
    Book book = new Book();
    book.setName("Harry Potter");
    book.setAuthorName("J. K. Rowling");
    return Response.status(200)


Result :-

REST XML Example

References :-

  1. JAXB Documentation
  2. @Produces Java Docs

That’s all for REST XML Example using Jersey 2 and JAXB. If you liked it, please share your thoughts in comments section and share it with others too.