REST JSON/XML response with Jersey

The below example describes publishing a simple JAX-RS REST JSON/XML response with Jersey 2.6 on Apache Tomcat.

1. Project Setup

Lets create a Jersey Maven Web Application Project with the below pom.xml

Note adding additional dependencies for JSON processing.

2. Code Application class

Code an Application class which is basically a configuration class for our REST Application

Our application class extends ResourceConfig, within the constructor of our application class we specify the packages to be scanned by Jersey for Resource Clasess (RESTful Webservices).

In the above example we as Jersey to scan the package com.heapcode.resource for any Resource classes, also we register Jackson Feature in order to work with JSON requests/responses.

3. Configure web.xml

The web.xml for the project looks something like this

In the web.xml  we declare the application class we just coded. In the next step we specify against which all URL patterns this servlet should be called or invoked. Here in this case “/*” which tells the servlet to be invoked for all URL patterns.

4. Code Model Class and DAO Class

Lets define a simple model class Employee having an Address class as below.

Note the annotation @XmlRootElement

Lets also code a Employee DAO class which gets a particular Employee based on id and all Employees.

5. Code Resource Class or Webservice class

1. In the above Resource class we specify that all the APIs within this class produce either JSON or XML response based on the one requested in Request.

6. Output:

We shall be using Postman – Rest Client addon for Google Chrome to invoke the service.

1. JSON response for all Employees.
Json Response

Json Response

2. JSON response for an Employee.

Jersey-JSON-Single

3. XML response for all Employees.

Jersey-XML-All

 4. XML response for an Employee.

Jersey-XML-Single

Note the output format is being set in the request by setting the Accept header.

7. Project Structure:

XMLJSONProjectStructure

Download-REST-Jersey-Maven-Project

I hope this has been useful for you and I’d like to thank you for reading. If you like this article, please leave a helpful comment and share it with your friends.

Leave a Reply

Your email address will not be published. Required fields are marked *