JSON example with Jersey + Jackson

Jersey uses Jackson to convert object to / form JSON. In this tutorial, we show you how to convert a “Track” object into JSON format, and return it back to user.

1. Dependency

To make Jersey support JSON mapping, declares “jersey-json.jar” in Maven pom.xml file.

Review the downloaded dependencies in your project classpath, Jackson and related libraries are inlcuded.

2. Integrate JSON with Jersey

In web.xml, declares “com.sun.jersey.api.json.POJOMappingFeature” as “init-param” in Jersey mapped servlet. It will make Jersey support JSON/object mapping.


File : web.xml – full example.

<web-app ...>

3. Simple Object

A simple “Track” object, later Jersey will convert it into JSON format.

package com.mkyong;
public class Track {
	String title;
	String singer;
	public String getTitle() {
		return title;
	public void setTitle(String title) {
		this.title = title;
	public String getSinger() {
		return singer;
	public void setSinger(String singer) {
		this.singer = singer;
	public String toString() {
		return "Track [title=" + title + ", singer=" + singer + "]";

4. JAX-RS with Jersey

Annotate the method with @Produces(MediaType.APPLICATION_JSON). Jersey will use Jackson to handle the JSON conversion automatically.

package com.mkyong.rest;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import com.mkyong.Track;
public class JSONService {
	public Track getTrackInJSON() {
		Track track = new Track();
		track.setTitle("Enter Sandman");
		return track;
	public Response createTrackInJSON(Track track) {
		String result = "Track saved : " + track;
		return Response.status(201).entity(result).build();

5. Demo

See demo for GET and POST request.

1. GET method
When URI pattern “/json/metallica/get” is requested, the Metallica classic song “Enter Sandman” will be returned in JSON format.

	"title":"Enter Sandman"
json jersey demo

2. POST method
To test post request, you can create a RESTful client (refer to this Jersey client APIs example), and “post” the json format string to URI pattern “/json/metallica/post“, the posted json string will be converted into “Track” object automatically.

Download Source Code

Download it – JSON-Support-Jersey-Example.zip (7 KB)


  1. Jackson Official Website
  2. JSON Support in Jersey
Tags :

About the Author

Founder of Mkyong.com and HostingCompass.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.