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

3 weeks ago codedestine 0

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

Let’s try to understand it with an example.

Example :-

Book.java

Create a bean class “Book” with few class members. This class will be used as an entity to receive a request from 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 receive a request from client in XML format.

import javax.xml.bind.annotation.XmlRootElement;

@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;
  }	
	
}

Dependency

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.

<dependency>
    <groupId>org.glassfish.jersey.media</groupId>
    <artifactId>jersey-media-moxy</artifactId>
    <version>2.26-b03</version>
</dependency>

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

import javax.ws.rs.Consumes;
import javax.ws.rs.PUT;
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;

@Path("books")
public class ConsumesAnnotationExample {

	@PUT
	@Consumes({MediaType.APPLICATION_XML,MediaType.APPLICATION_JSON})
	@Produces(MediaType.TEXT_PLAIN)
	@Path("/{id}")
	public Response getAllBooks(@PathParam("id") String bookId,Book bookData){
		return Response.status(200)
					   .entity("Saved :- "+bookData.getId()).build();
	}
	
}

Result :-

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

JAX RS @Consumes

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

JAX RS @Consumes

References :-

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

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