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.


	<dependency>
		<groupId>com.sun.jersey</groupId>
		<artifactId>jersey-server</artifactId>
		<version>1.8</version>
	</dependency>

	<dependency>
		<groupId>com.sun.jersey</groupId>
		<artifactId>jersey-json</artifactId>
		<version>1.8</version>
	</dependency>	
Note
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.


	<init-param>
		<param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
		<param-value>true</param-value>
	</init-param>

File : web.xml – full example.


<web-app ...>

  <servlet>
	<servlet-name>jersey-serlvet</servlet-name>
	<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
	<init-param>
		<param-name>com.sun.jersey.config.property.packages</param-name>
		<param-value>com.mkyong.rest</param-value>
	</init-param>
	<init-param>
		<param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
		<param-value>true</param-value>
	</init-param>
	<load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
	<servlet-name>jersey-serlvet</servlet-name>
	<url-pattern>/rest/*</url-pattern>
  </servlet-mapping>

</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;
	}

	@Override
	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;

@Path("/json/metallica")
public class JSONService {

	@GET
	@Path("/get")
	@Produces(MediaType.APPLICATION_JSON)
	public Track getTrackInJSON() {

		Track track = new Track();
		track.setTitle("Enter Sandman");
		track.setSinger("Metallica");

		return track;

	}

	@POST
	@Path("/post")
	@Consumes(MediaType.APPLICATION_JSON)
	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.


{
	"singer":"Metallica",
	"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)

References

  1. Jackson Official Website
  2. JSON Support in Jersey

About the Author

author image
mkyong
Founder of Mkyong.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.

Comments

Leave a Reply

avatar
newest oldest most voted
sallap
Guest
sallap

What if the passing object is not simple ? Or what if you object ‘Track’ extending another class, And I want to pass attributes of both the classes to my web service, in a single JSON string ?

Roberto Fonseca
Guest
Roberto Fonseca

Is there a way to use a JSON @PathParam to populate an Entity

public ObjectNode getPDF( @PathParam(“params”) MyParameters params )

raviteja
Guest
raviteja

Can some one help me
HTTP Status 404 – /RESTfulExample/

raviteja
Guest
raviteja

HTTP Status 500 – Servlet.init() for servlet jersey-serlvet threw exception

leon
Guest
leon

great post!!
Thanks!

Jesse Boyd
Guest
Jesse Boyd

com.sun.jersey.spi.container.servlet.ServletContainer is depricated and replaced with org.glassfish.jersey.containers it’s a bit of a mess and not well documented how to get all the new dependencies.

Rodrigo Caballero
Guest
Rodrigo Caballero

Not actual working code anymore.
Can you update an updated version of your project?

Juan
Guest
Juan
Hello buddy, excellent info and awesome Tuto!, I have a question, I made a static example based on your knowledge, I’mm getting the following structure: { “nombre”: “Juan”, “edad”: “22”, “clave”: “paciente01”, “padecimientos”: [ { “nombrePadecimiento”: “Manía Cardiaca”, “clave”: “pa01” }, { “nombrePadecimiento”: “Manía Pulmonaría”, “clave”: “pa02” } ], “citas”: [ { “fecha”: “2017-01-01”, “lugar”: “Hospital Luz” }, { “fecha”: “2017-02-02”, “lugar”: “Hospital Oscuridad” } ] } But I’d like to send a parent name of all object. for example “Paciente”, on the to of the Json. Could you help me?
John steven
Guest
John steven

NIce info !

David Brossard
Guest
David Brossard

I tried this example straight OOTB on Apache Tomcat and nothing happens at all… What am I missing?

Naveen Shyam Reuban
Guest
Naveen Shyam Reuban

How to implement HTTP PUT ? @PUT – would it have PathParam & the data ? Can you provide an example to this newbie on JERSEY REST ?

Nishanth
Guest
Nishanth

Why are we not getting back the root element (Track) in json in response. What should we do for the json root element to be accepted in the request.

Auf Pathor
Guest
Auf Pathor

why?? why?? why??

koooo
Guest
koooo

fuck….fuck….fuck….

Dante Basso
Guest
Dante Basso

Hello,

I’m trying to do something like this, but I need send a array of one object: like:

[{“value”:”200″,”index”:1},{“value”:”200″,”index”:2},{“value”:”200″,”index”:3},{“value”:”200″,”index”:4},{“value”:”200″,”index”:5},{“value”:”200″,”index”:6},{“value”:”200″,”index”:7},{“value”:”200″,”index”:8},{“value”:”200″,”index”:9},{“value”:”200″,”index”:10}]

But in server Side I got error! How can I make the code:

@POST
@Path(“/calceven”)
@Consumes(MediaType.APPLICATION_JSON)
public Response calcEvenIndexes(MyNumber[] lista) {
AND
public Response calcEvenIndexes(List lista) {

And I got error: HTTP Status 415 – Unsupported Media Type

I try in both parameters this:
@Consumes(MediaType.TEXT_PLAIN)

But the erro still there…
How can resolve my problem?

Sanjeev Pandey
Guest
Sanjeev Pandey

Use JSONArray. Put the map in JSONArray, you will get the expected result.

http://java-application-programming.blogspot.in/

Jason Wheeler
Guest
Jason Wheeler

thanks for this, I didn’t notice when trying to run the example

Arun
Guest
Arun

Hi Mkyong , please post the tutorial with latest version of jackson/faster xml which is 2.x

Avinash Kodakandla
Guest
Avinash Kodakandla

post request not working

Muhammad Gelbana
Guest
Muhammad Gelbana

Everyone should note that this tutorial is almost 4 years old. So it adheres to an old specification and and version of Jersey.

A message to the author, would you kindly make a tutorial for a webapp (servlets only) in jersey that provides Json mapping ? I am completely lost and the user guide aren’t helpful at all.

Matt
Guest
Matt

Why include junit in pom.xml if it’s not used in the example?

trackback
JAX-RS TUTORIALS | BUYWORKSELL

[…] JSON example with Jersey + Jackson Jersey + Jackson to map object to and from JSON. […]

Diego
Guest
Diego

Where is web.xml file supposed to be placed? I use Tomcat as server. Got working with NetBeans

Aryan
Guest
Aryan

it already have an web.xml file created with every web application project just openit and edit.

Levan
Guest
Levan

Hi.

Thanks for the tutorial.

You could update the outdated link to the JSON support in Jersey page. The new link is: https://jersey.java.net/documentation/latest/media.html#json

abhi
Guest
abhi

What is the “jersey-json.jar” version ?

i m facing an and error like

Jersey: No WebApplication provider is present

jersey-servlet is not able to intializate

wat is the version

Sushil Kumar
Guest
Sushil Kumar

HI Mkyong

I tried this example and i’m getting javax.ws.rs.WebApplicationException: com.sun.jersey.api.MessageException: A message body writer for Java class com.kaysush.ytgrabber.yt.DownloadResource, and Java type class com.kaysush.ytgrabber.yt.DownloadResource, and MIME media type application/json was not found exception.

I think i’m missing some dependencies. After reading the comments i found out that i can use jersey bundle for all the dependencies but i want all of them to be separate and hence request you. Can you please provide a tentative list of all the dependencies that are required to run the above example.

abhi
Guest
abhi

Even i am facing the same !

Nikita Shah
Guest
Nikita Shah

What is the solution to your problem ?

Ezra
Guest
Ezra

Am not sure on why this exception, but if you are facing “Mesage body writer” issue, add genson to your dependency, it works. for more info check http://owlike.github.io/genson/

com.owlike
genson
1.3

Sriharsha g.r.v
Guest
Sriharsha g.r.v

Thanks for pointing out.Genson is needed because,we need to tell jersey that the java class should be converted to Json by checking specifications like setter/getter classes if present or not.

Just like we need Jaxb jar(which is included in jdk 1.6) for converting Java class to xml.

bhoomi patel
Guest
bhoomi patel

Thanks for this..its saved my time

Binh Nguyen Thanh
Guest
Binh Nguyen Thanh

Thanks, this post is useful to me.

priya
Guest
priya

tried the example in myeclipse ide with websphere7 and getting the below error

00000110 servlet E com.ibm.ws.webcontainer.servlet.ServletWrapper init SRVE0100E: Uncaught init() exception created by servlet jersey-serlvet in application SampleProject: java.lang.NoSuchMethodError: org/objectweb/asm/ClassReader.accept(Lorg/objectweb/asm/ClassVisitor;I)V

at com.sun.jersey.spi.scanning.AnnotationScannerListener.onProcess(AnnotationScannerListener.java:133)

at com.sun.jersey.core.spi.scanning.uri.FileSchemeScanner$1.f(FileSchemeScanner.java:86)

at com.sun.jersey.core.util.Closing.f(Closing.java:71)

at com.sun.jersey.core.spi.scanning.uri.FileSchemeScanner.scanDirectory(FileSchemeScanner.java:83)
……………………..

00000110 extension E com.ibm.wsspi.webcontainer.extension.WebExtensionProcessor createServletWrapper Error occured while preparing the servlet for initialization.

javax.servlet.ServletException: SRVE0207E: Uncaught initialization exception created by servlet

Added the jars- asm-all.jar, cglib-nodep,jackson and jersey jars

i removed all other conflictings asm jars still the error exists

please let me know what is wrong.

nizar
Guest
nizar

Hello,
how post an object java from html form ?
example if i have a html form within
how can post a json to get a Track object ?

priya
Guest
priya
Pradip Bhatt
Guest
Pradip Bhatt

Really its very nice tutorial. REally appreciate..

MkYong.. reallt we are so lucky…

Prakash
Guest
Prakash

Loved these tutorials man thanks alot!.

Jakes
Guest
Jakes

Hi Mkyong

Thanks, that was nice and simple example
Next I am trying to convert the JSON received on client side to “Track” object.
Does Jersey provide me any way to generate any client stubs/bindings/classes that I can use on client side to convert the received JSON to java object.

Thanks