JAX RS @Produces both XML and JSON with Example – RESTful Web Services Tutorial

2 years ago Lalit Bhagtani 0

In this tutorial, we will learn to produce both XML and JSON response from a single method on server side depending upon the client request. You can learn more about JAX RS @Produces annotation here.

Let’s try to understand it with an example.

Example :-


Create a bean class “Book” with few class members. This class will be used as an entity to send a response to client in JSON format. We also annotated our bean class with @XmlRootElement marking it as a root element, so that we can use same bean class to send a response to client in XML format.

import javax.xml.bind.annotation.XmlRootElement;

public class Book {

  private String id;
  private String name;
  private String authorName;
  private int volumeNumber;
  public String getId() {
    return id;
  public String getName() {
    return name;
  public void setName(String name) {
    this.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;


Add one dependency in pom file of your project. This dependency is required by jersey library to convert your bean class in to JSON format and vice versa.


In this example of JAX-RS @Produces, we will hit this URL <base URL>/books/1 with HTTP GET method to get the book resource of id 1 in JSON format and in XML format.

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

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 :-

To get a response in JSON format, we will send “Accept : application/json” key-value in the header of the request.

JAX RS @Produces

To get a response in XML format, we will send “Accept : application/xml” key-value in the header of the request.

JAX RS @Produces

References :-

  1. @Consumes Java Docs
  2. @Produces Java Docs

That’s all for JAX RS @Produces both XML and JSON with Example. If you liked it, please share your thoughts in comments section and share it with others too.