JAX RS @Produces both XML and JSON with Example – RESTful Web Services Tutorial
7 years ago Lalit Bhagtani 1
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 :-
Book.java
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; @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 @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; @Path("books") public class ProducesAnnotationExample { @GET @Produces({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML}) @Path("/{id}") public Response getAllBooks(@PathParam("id") String bookId){ Book book = new Book(); book.setId(bookId); book.setName("Harry Potter"); book.setVolumeNumber(1); book.setAuthorName("J. K. Rowling"); return Response.status(200) .entity(book).build(); } }
Result :-
To get a response in JSON format, we will send “Accept : application/json” key-value in the header of the request.
To get a response in XML format, we will send “Accept : application/xml” key-value in the header of the request.
References :-
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.
1 thought on “JAX RS @Produces both XML and JSON with Example – RESTful Web Services Tutorial”
clear and accurate tutorial. thanks!