REST API JSON Example using Jersey 2 and Media Moxy- RESTful Web Services Tutorial

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

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) { = 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 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.


public class JSONExample {

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


References :-

  1. @Produces Java Docs

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.