REST API JSON Example using Jersey 2 and Media Moxy- RESTful Web Services Tutorial
6 years ago Lalit Bhagtani 0
REST API JSON Example :- In this tutorial, we will learn to produce JSON response using Jersey 2 and Media Moxy.
Media Moxy is used to convert java object to JSON response. Jersey 2 libraries does not contains Media Moxy libraries, so there is a need to add Media Moxy related dependency in pom.xml file of your project.
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.
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 REST API JSON Example, we will hit this URL <base URL>/books/1 to get the book resource of id 1. To get a response in JSON format, we will annotate the method with @Produces annotation with APPLICATION_JSON MIME media type.
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 JSONExample { @GET @Produces(MediaType.APPLICATION_JSON) @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 :-
References :-
That’s all for REST API JSON Example using Jersey 2 and Media Moxy. If you liked it, please share your thoughts in comments section and share it with others too.