How To Return Multiple Content Type From Same Method in Jersey REST Service

Till now we have seen examples of REST service which return different type of content such as XML or JSON.  However we used different methods to handle each content type.  In this example we will see how to return different types of contents from the same method.

As you will see it is very easy to do this with a common method.

The key part is the @Produces({MediaType.APPLICATION_XML,MediaType.APPLICATION_JSON})

This annotation denotes that the method can output XML or JSON content.

You might be wondering how the method decides which type of content to return.  The is the the Accept header.  The client can pass Accept header values such as application/xml or application/json.  Depending on the value of the header, the response gets converted into proper content type and sent back to the client.  In case Accept header is not sent then application/xml is sent back as it has higher priority.

package com.freetipscentral;
import java.util.ArrayList;
import java.util.List;
import com.freetipscentral.domain.Book;
public class MultipleContentFromServiceMethod {
	public Response getBook(@Context HttpHeaders headers, @PathParam("bookId") int bookId) {
		List<Book> books = getBooks();
		for(Book book : books) {
			if(book.getSerialNumber() == bookId) {
				return Response.ok(book).build();
		return Response.status(Status.NOT_FOUND).build();
	private List<Book> getBooks() {
		List<Book> books = new ArrayList<Book>();
		Book book1 = new Book();
		book1.setName("Head First Java");
		Book book2 = new Book();
		book2.setName("The Clean Coder");
		return books;	

package com.freetipscentral.domain;
public class Book {
	String name;
	int serialNumber;
	public Book() {}
	public Book(String name, int serialNumber) { = name;
		this.serialNumber = serialNumber;
	public String getName() {
		return name;
	public void setName(String name) { = name;
	public int getSerialNumber() {
		return serialNumber;
	public void setSerialNumber(int serialNumber) {
		this.serialNumber = serialNumber;
	public String toString() {
		return serialNumber + " "  + name;

Url to Invoke


Output With Accept header value application/xml

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<name>Head First Java</name>

Output With Accept header value application/json

"name": "Head First Java",
"serialNumber": 1