How To Create a Rest Web Service with JSON response in Jersey

In a previous tutorial we learnt how to create a hello world rest service.  This tutorial is a continuation of the previous tutorial.  Here you will learn how to get a JSON response from Rest web service.  Ensure that you have a work space setup similar to the one you had in the previous tutorial.  The below example will show how to get a JSON object from  Rest Service.

Here are the steps.

  1. Write a Rest Service which returns a Book object.
  2. Create a Book domain object.
  3. Run the application and access the service.

Write a Rest Service

JerseyRestServiceWithJSON
package com.freetipscentral;
 
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.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
 
import com.freetipscentral.domain.Book;
 
@Path("/books")
public class JerseyRestServiceWithJSON {
 
	@GET
	@Produces(MediaType.APPLICATION_JSON)
	@Path("{bookId}")
	public Book getBook(@Context HttpHeaders headers, @PathParam("bookId") int bookId) {
		Book book = null;
		Book book1 = new Book("Harry Potter",1);
		Book book2 = new Book("Harry Potter",2);
 
		if(bookId == 1) {
			book = book1;
		} else {
			book = book2;
		}
		return book;
	}
}

Book class

package com.freetipscentral.domain;
 
public class Book {
 
	String name;
	int serialNumber;
 
	public Book(String name, int serialNumber) {
		this.name = name;
		this.serialNumber = serialNumber;
	}
 
	public String getName() {
		return name;
	}
	public void setNam(String name) {
		this.name = name;
	}
	public int getserialNumber() {
		return serialNumber;
	}
	public void setSerialNumber(int serialNumber) {
		this.serialNumber = serialNumber;
	}
 
	public String toString() {
		return serialNumber + " "  + name;
	}
 
}

Here is the output

{"name":"Harry Potter","serialNumber":1}

I will be posting a video of the steps also soon.