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>
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"
}
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.







Kenneth Jefferson…
[...]c We are a gaggle of volunteers and starting a new scheme in our community. Y z9[...]…
HI,
I am using the Jersey+spring in my Project.
My problem is that,
If Some properties in my POJO is null, then these properties also being converted in JSON having value as null.
JSON Response:
{
“responseStatus”:”Success”,
“name”:”Anthony”,
“company”:null,
“address” : null
}
How to avoid sending null property in the JSON response to UI.
I have the Dependency mentioned in this example in POM, and Declared the POJOMappingFeature in Web.xml too.
Please help
Posted this on a different thread, but this one may be the most appropriate.
I have spent nearly 20 hours to get “JSONP” to work with Jersey to overcome the cross-domain issue.
Passing on…
Here is the JavaScript client side:
Here is the Java Server side
The trick is to match the callback parameter name (callback in this case) and to return a JSONWithPadding Object
The server side should be improved to return a collection instead of a simple Track object
web.xml is as follows,
Jersey REST Service com.sun.jersey.spi.container.servlet.ServletContainer com.sun.jersey.config.property.packages com.junctiontv.subm.ws com.sun.jersey.api.json.POJOMappingFeature true 1 Jersey REST Service /rest/*I am trying to return a simple json formated java object using jersey (1.12).
But getting following error — SEVERE: A message body writer for Java class com.junctiontv.subm.model.Subscriber, and Java type class com.junctiontv.subm.model.Subscriber, and MIME media type application/json wa
s not found.
Can you please help.
web.xml is as follows,
Jersey REST Service com.sun.jersey.spi.container.servlet.ServletContainer com.sun.jersey.config.property.packages com.junctiontv.subm.ws com.sun.jersey.api.json.POJOMappingFeature true 1 Jersey REST Service /rest/*I have added jersey-json jar in the path still getting above error
here is the entire error stack
You need to add the jackson jars to the classpath.
If you are using maven, then you need to add these dependencies:
org.codehaus.jackson
jackson-core-asl
1.9.6
org.codehaus.jackson
jackson-mapper-asl
1.9.6
org.codehaus.jackson
jackson-jaxrs
1.9.6
org.codehaus.jackson
jackson-xc
1.9.6
Hi
I am new to restful webservices. I am not sure if I need to add Jersey dependencies on my project ear file or war file. Could you please explain.
Thanks
Sandy
You’re in EJB development, right? Sorry, long time didn’t touch it.
If your ear need to use it, then group it together, otherwise group with the war. Just make sure it;s available the project classpath.
Sorry i didn’t get. I am not using EJBs. I am using simple POJO.
What changes are required and which files if i need list of tracks like:
List : [
{ "singer":"Metallica-0", "title":"Enter Sandman-0" },
{ "singer":"Metallica-1", "title":"Enter Sandman-1" },
{ "singer":"Metallica-2", "title":"Enter Sandman-2" }
]
Could you pls change the client as well.
Regards
Dharam
Pls tell from post method point of view.
How to write a service consuming a JSON string as a parameter.
I mean, method should consume directly a JSON Object instead of consuming as a string and parsing to JSON.
Please provide me solution.
Hello Mkyong,
I solved the problem by using “@XmlRootElement” annotation in the Track class.
@XmlRootElement
public class Track {
String title;
String singer;
public String getTitle() {
return title;
}
…
The jars I used was
1. jersey-core-1.8.jar
2. jersey-json-1.8.jar
3. jersey-server-1.8.jar
4. jaxb-impl.jar
Hello Mkyong,
Thanks for the good example.
I am using Netbeans 6.9 + Glass Fish 3.1 and EJB 3.0
I am able to run the Jersey hello world example. I have used the above example u you have provided. But I am getting the followin error.
javax.ws.rs.WebApplicationException
public Track getTrackInJSON() {
Track track = new Track();
track.setTitle(“Enter Sandman”);
track.setSinger(“Metallica”);
return track;
}
But when I do this return track.toString() it works fine.
Thanks in advance.
Please provide your last caused by error message.
I try to parse List<Map> from json.
this is what i send (firebug see it this way):
{“data”:[{"name":"Raport","rows":[{"D?ugo??":"58,403","Kilometra? ko?cowy":"157,688","Kilometra? pocz?tkowy":"99,285","Nazwa odcinka":"PILAWA - POWAZE","Numer linii":"12","Nazwa linii":"SKIERNIEWICE - LUKÓW","Kod odcinka":"F"}]}]}
this is my jersey method:
My jersey method isn’t fired. I got “HTTP ERROR: 415 Unsupported Media Type” in browser.
What could be reason for this?
did you include “jersey-json.jar”? Look like your app server doesn’t support json as return type. Refer to your server documentation.
Thanks buddy you saved my life with this post :))
Hi,
I’m getting this error when loading the URL on firefox:
SEVERE: A message body writer for Java class com.eveo.connect.ws.Track, and Java type class com.eveo.connect.ws.Track, and MIME media type application/json was not found
Sep 16, 2011 11:45:03 AM com.sun.jersey.spi.container.ContainerResponse write
SEVERE: The registered message body writers compatible with the MIME media type are:
*/* ->
Any idea why it can’t covert Track into JSON? Thanks
is “jersey-json” in your project classpath?
[...] “GET” and “POST” requests to REST service that created in this “Jersey + Json” example.1. Jersey Client DependencyTo use Jersey client APIs, declares [...]