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
Tags :

About the Author

mkyong
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.

Comments

  • Pingback: Blue Coaster33()

  • Pingback: JAX-RS TUTORIALS | BUYWORKSELL()

  • Diego

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

  • 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

    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

  • http://kaysush.wordpress.com 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

      Even i am facing the same !

  • Binh Nguyen Thanh

    Thanks, this post is useful to me.

  • 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

    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 ?

  • Pradip Bhatt

    Really its very nice tutorial. REally appreciate..

    MkYong.. reallt we are so lucky…

  • 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 ?

  • Prakash

    Loved these tutorials man thanks alot!.

  • 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

  • viny

    I’m having the following problem can anyone give me a hand pleas..

    java.lang.AbstractMethodError
    at org.codehaus.jackson.map.AnnotationIntrospector$Pair.findDeserializer(AnnotationIntrospector.java:1335)
    at org.codehaus.jackson.map.deser.BasicDeserializerFactory.findDeserializerFromAnnotation(BasicDeserializerFactory.java:675)
    at org.codehaus.jackson.map.deser.BeanDeserializerFactory.createBeanDeserializer(BeanDeserializerFactory.java:535)
    at org.codehaus.jackson.map.deser.StdDeserializerProvider._createDeserializer(StdDeserializerProvider.java:432)
    at org.codehaus.jackson.map.deser.StdDeserializerProvider._createAndCache2(StdDeserializerProvider.java:341)
    at org.codehaus.jackson.map.deser.StdDeserializerProvider._createAndCacheValueDeserializer(StdDeserializerProvider.java:321)
    at org.codehaus.jackson.map.deser.StdDeserializerProvider.findValueDeserializer(StdDeserializerProvider.java:167)
    at org.codehaus.jackson.map.deser.StdDeserializerProvider.findTypedValueDeserializer(StdDeserializerProvider.java:188)
    at org.codehaus.jackson.map.ObjectMapper._findRootDeserializer(ObjectMapper.java:2820)
    at org.codehaus.jackson.map.ObjectMapper._readValue(ObjectMapper.java:2690)
    at org.codehaus.jackson.map.ObjectMapper.readValue(ObjectMapper.java:1308)
    at org.codehaus.jackson.jaxrs.JacksonJsonProvider.readFrom(JacksonJsonProvider.java:419)
    at com.sun.jersey.json.impl.provider.entity.JacksonProviderProxy.readFrom(JacksonProviderProxy.java:139)
    at com.sun.jersey.spi.container.ContainerRequest.getEntity(ContainerRequest.java:488)
    at com.sun.jersey.server.impl.model.method.dispatch.EntityParamDispatchProvider$EntityInjectable.getValue(EntityParamDispatchProvider.java:123)
    at com.sun.jersey.server.impl.inject.InjectableValuesProvider.getInjectableValues(InjectableValuesProvider.java:46)
    at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$EntityParamInInvoker.getParams(AbstractResourceMethodDispatchProvider.java:153)
    at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$VoidOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:166)
    at com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:75)
    at com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:302)
    at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
    at com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:108)
    at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
    at com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:84)
    at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1511)
    at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1442)
    at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1391)
    at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1381)
    at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:416)
    at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:538)
    at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:716)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:511)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1166)
    at com.google.appengine.api.socket.dev.DevSocketFilter.doFilter(DevSocketFilter.java:74)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
    at com.google.appengine.tools.development.ResponseRewriterFilter.doFilter(ResponseRewriterFilter.java:123)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
    at com.google.appengine.tools.development.HeaderVerificationFilter.doFilter(HeaderVerificationFilter.java:34)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
    at com.google.appengine.api.blobstore.dev.ServeBlobFilter.doFilter(ServeBlobFilter.java:61)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
    at com.google.apphosting.utils.servlet.TransactionCleanupFilter.doFilter(TransactionCleanupFilter.java:43)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
    at com.google.appengine.tools.development.StaticFileFilter.doFilter(StaticFileFilter.java:125)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
    at com.google.appengine.tools.development.BackendServersFilter.doFilter(BackendServersFilter.java:97)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
    at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:388)
    at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216)
    at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:182)
    at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:765)
    at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:418)
    at com.google.appengine.tools.development.DevAppEngineWebAppContext.handle(DevAppEngineWebAppContext.java:94)
    at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
    at com.google.appengine.tools.development.JettyContainerService$ApiProxyHandler.handle(JettyContainerService.java:383)
    at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
    at org.mortbay.jetty.Server.handle(Server.java:326)
    at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:542)
    at org.mortbay.jetty.HttpConnection$RequestHandler.content(HttpConnection.java:938)
    at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:755)
    at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:218)
    at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:404)
    at org.mortbay.io.nio.SelectChannelEndPoint.run(SelectChannelEndPoint.java:409)
    at org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:582)

    • Lu

      Anyone fixed the java.lang.AbstractMethodError that some folks were getting with the client app I’m getting it too?

  • koo

    Hi, i import ur example to workspace. But i get tis error.Please help

    type Status report
     
    message /RestfulExample/rest/json/metallica/post
     
    description The requested resource (/RestfulExample/rest/json/metallica/post) is not available.
    • joahnn

      Hi,
      I have the same problem, but with my integration tests.

      &lt;plugin&gt;
      				&lt;groupId&gt;org.codehaus.mojo&lt;/groupId&gt;
      				&lt;artifactId&gt;tomcat-maven-plugin&lt;/artifactId&gt;
      				&lt;configuration&gt;
      					&lt;fork&gt;true&lt;/fork&gt;
      				&lt;/configuration&gt;
      				&lt;executions&gt;
      					&lt;execution&gt;
      						&lt;id&gt;run-tomcat&lt;/id&gt;
      						&lt;phase&gt;pre-integration-test&lt;/phase&gt;
      						&lt;goals&gt;
      							&lt;goal&gt;run&lt;/goal&gt;
      						&lt;/goals&gt;
      					&lt;/execution&gt;
      				&lt;/executions&gt;
      			&lt;/plugin&gt;
    • Manuel Loayza

      I had a similar problem, but It was my classes with annotation for REsta was in other package. I modified the init-param for rest servlet as follow (add more packages separated with comma).

      com.sun.jersey.config.property.packages
      com.melg.web, com.melg.jerseydemo.web.client

  • thangam

    I am running the above code in RAD and deploying in was7.0 server
    I have jersey-bundle-1.11.jar in the web-inf/lib folder
    when I run the restful service i still get the following error
    [10/25/12 8:58:26:316 PDT] 0000002c ContainerResp E The registered message body writers compatible with the MIME media type are:
    text/plain ->
    com.sun.jersey.core.impl.provider.entity.StringProvider
    com.sun.jersey.core.impl.provider.entity.ReaderProvider
    */* ->
    com.sun.jersey.core.impl.provider.entity.FormProvider
    com.sun.jersey.core.impl.provider.entity.MimeMultipartProvider
    com.sun.jersey.core.impl.provider.entity.StringProvider
    com.sun.jersey.core.impl.provider.entity.ByteArrayProvider
    com.sun.jersey.core.impl.provider.entity.FileProvider
    com.sun.jersey.core.impl.provider.entity.InputStreamProvider
    com.sun.jersey.core.impl.provider.entity.DataSourceProvider
    com.sun.jersey.core.impl.provider.entity.XMLJAXBElementProvider$General
    com.sun.jersey.core.impl.provider.entity.ReaderProvider
    com.sun.jersey.core.impl.provider.entity.DocumentProvider
    com.sun.jersey.core.impl.provider.entity.StreamingOutputProvider
    com.sun.jersey.core.impl.provider.entity.SourceProvider$SourceWriter
    com.sun.jersey.server.impl.template.ViewableMessageBodyWriter
    com.sun.jersey.json.impl.provider.entity.JSONJAXBElementProvider$General
    com.sun.jersey.core.impl.provider.entity.XMLRootElementProvider$General
    com.sun.jersey.core.impl.provider.entity.XMLListElementProvider$General
    com.sun.jersey.json.impl.provider.entity.JSONRootElementProvider$General
    com.sun.jersey.json.impl.provider.entity.JSONListElementProvider$General

    [10/25/12 8:58:26:316 PDT] 0000002c ContainerResp E Mapped exception to response: 500 (Internal Server Error)
    javax.ws.rs.WebApplicationException: com.sun.jersey.api.MessageException: A message body writer for Java class com.con_way.rest.Track, and Java type class com.con_way.rest.Track, and MIME media type text/plain was not found
    at com.sun.jersey.spi.container.ContainerResponse.write(ContainerResponse.java:285)
    at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1437)
    at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1349)
    at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1339)

  • aimanSD

    Hi, mkyong great tutorial…it help me to understand better.
    Do you have example on transfer .zip file using jersey and json?

    Thank you for your help…

  • Pingback: Including Class name in POJO – JSON Marshalling | Jisku.com - Developers Network()

  • Ran
     

    tag, for examples :

    &lt;init-param&gt;
    	&lt;param-name&gt;com.sun.jersey.api.json.POJOMappingFeature&lt;/param-name&gt;
    	&lt;param-value&gt;true&lt;/param-value&gt;
    &lt;/init-param&gt;
     XML here

    This code fragment was very helpful.
    i didn’t write at all and it wasn’t working.
    As I add it i got the JSON response.
    Thanks alot…

    and sorry for spamming my prev post didn’t parsed well so…

  • Ran


    com.sun.jersey.api.json.POJOMappingFeature
    true

    This code fragment was very helpful.
    i didn’t write at all and it wasn’t working.
    As I add it i got the JSON response.
    Thanks alot…

  • http://fernandofranzini.wordpress.com Fernando Franzini

    Tomcat 7.0.29 with jersey 1.12… JSON format doen’t work!! I’ve received HTTP STATUS 415 in rest client invocation….
    Running on the container Grizzly the error does not happen…only with tomcat ..! You know something about it?

    • http://i-develop.be Steven Willems

      Hi Fernando,

      were you able to solve your issue? I’m having the same error. Works on grizzly, but not on tomcat.
      Any help appreciated.

      Steven

      • Ghershun Nikolai

        Had same problem. Include of jackson-all.jar resolved the problem.

        Regards,
        Nikolai.

  • Andrew

    Hello. But What if I want to return XML and JSON? So I need to create 2 equialelnt classes? One annotated with JAXB annotations(for XML) and second class declared in web.xml:

    com.sun.jersey.api.json.POJOMappingFeature
    true

    ?

  • Bhawesh
  • Bhawesh

    Hello mkyong
    Getting Error while sending post request ,as shown above can you help me out

    Thanks

  • Bhawesh

    hello mkyong

    I am not able to send the post request so can you help me out how to send post request

    Thanks

  • Gamnacke

    I’m trying out the POJOMappingFeature with jersey 1.12 and had trouble getting it working. Finally I nailed it down to specifying the packages to scan in the init param “com.sun.jersey.config.property.packages” web.xml. This needs to left undefined OR you’ll have to specify the package “org.codehaus.jackson.jaxrs” for the Provider-class JacksonJsonProvider to registered.

  • HA

    Hi Mkyong,
    Thanks for the wonderful post.
    When I follow the steps and try to run my app I get the following error. I am using JBoss AS7.1. PLease help.

    /*************************************/
    java.lang.AbstractMethodError
    org.codehaus.jackson.map.AnnotationIntrospector$Pair.findSerializer(AnnotationIntrospector.java:1148)
    org.codehaus.jackson.map.ser.BasicSerializerFactory.findSerializerFromAnnotation(BasicSerializerFactory.java:362)
    org.codehaus.jackson.map.ser.BeanSerializerFactory.createSerializer(BeanSerializerFactory.java:252)
    org.codehaus.jackson.map.ser.StdSerializerProvider._createUntypedSerializer(StdSerializerProvider.java:782)
    org.codehaus.jackson.map.ser.StdSerializerProvider._createAndCacheUntypedSerializer(StdSerializerProvider.java:735)
    org.codehaus.jackson.map.ser.StdSerializerProvider.findValueSerializer(StdSerializerProvider.java:344)
    org.codehaus.jackson.map.ser.StdSerializerProvider.findTypedValueSerializer(StdSerializerProvider.java:420)
    org.codehaus.jackson.map.ser.StdSerializerProvider._serializeValue(StdSerializerProvider.java:601)
    org.codehaus.jackson.map.ser.StdSerializerProvider.serializeValue(StdSerializerProvider.java:256)
    org.codehaus.jackson.map.ObjectMapper.writeValue(ObjectMapper.java:1604)
    org.codehaus.jackson.jaxrs.JacksonJsonProvider.writeTo(JacksonJsonProvider.java:558)
    com.sun.jersey.json.impl.provider.entity.JacksonProviderProxy.writeTo(JacksonProviderProxy.java:160)
    com.sun.jersey.spi.container.ContainerResponse.write(ContainerResponse.java:306)
    com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1451)
    com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1363)
    com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1353)
    com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:414)
    com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:537)
    com.sun.jersey.spi.container.servlet.ServletContainer.service(Serv
    /*************************************/

    • Sunny Anand

      Even I’m getting the same error with Tomact..
      Please help Mkyong.

    • Rafael

      The same is happening to me. I’m running on Jetty.

      Please, help! :)

  • http://beknown.com/ayaz.pasha Ayaz

    Hi,

    My REST service call returns me

     {&quot;param1&quot;:&quot;value1&quot;, &quot;param2&quot;:&quot;value2&quot;,....&quot;paramN&quot;:&quot;valueN&quot;}

    But, I want it to return

     [&quot;param1&quot;:&quot;value1&quot;, &quot;param2&quot;:&quot;value2&quot;,....&quot;paramN&quot;:&quot;valueN&quot;]

    What are the changes I need to make in the code below?

    @GET
    @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_JSON})
    public List&lt;com.abc.def.rest.model.SimplePojo&gt; getSomeList() {
    	/* 
                    Do something
            */
            return listOfPojos;
    }

    Thanks!

    • Ran

      I think its cos you return a list and a list in json syntaxed like {…}
      so try to return an array to get the json syntax you want like […]

  • Matteo

    Great tutorial, as usual for you, Mkyong! Thanks a lot!

  • Pingback: Kenneth Jefferson()

  • Pawan

    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

  • Christophe

    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:

    $.getJSON(&quot;http://localhost:8080/rest/json/metallica/get?callback=?&quot;,
    	{},
    	function(data) {
    		$(&quot;#status2&quot;).html( &quot;&lt;h2&gt;&quot; + data.singer + &quot; &quot; + data.title + &quot;&lt;h2&gt;&quot;);
    	}
    );

    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

    package com.pacsman.jersey;
     
    import javax.ws.rs.Consumes;
    import javax.ws.rs.DefaultValue;
    import javax.ws.rs.GET;
    import javax.ws.rs.POST;
    import javax.ws.rs.Path;
    import javax.ws.rs.Produces;
    import javax.ws.rs.QueryParam;
    import javax.ws.rs.core.MediaType;
    import javax.ws.rs.core.Response;
    import com.mkyong.Track;
    import com.sun.jersey.api.json.JSONWithPadding;
     
    @Path(&quot;/json/metallica&quot;)
    public class JSONService {
     
    	@GET
    	@Path(&quot;/get&quot;)
    	@Produces(&quot;application/x-javascript&quot;)
    	public JSONWithPadding getTrackInJSON(
    			@QueryParam(&quot;callback&quot;) @DefaultValue(&quot;CBParamIsMissing&quot;) String jsoncallback) {
    		Track track = new Track();
    		track.setTitle(&quot;Enter Sandman&quot;);
    		track.setSinger(&quot;Metallica3&quot;);
     
    		return new JSONWithPadding(track, jsoncallback);
    	}
    }
  • jeet

    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/*
  • jeet

    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

     Mar 9, 2012 8:25:32 PM com.sun.jersey.spi.container.ContainerResponse write
    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
    Mar 9, 2012 8:25:32 PM com.sun.jersey.spi.container.ContainerResponse write
    SEVERE: The registered message body writers compatible with the MIME media type are:
    application/json -&gt;
      com.sun.jersey.json.impl.provider.entity.JSONJAXBElementProvider$App
      com.sun.jersey.json.impl.provider.entity.JSONArrayProvider$App
      com.sun.jersey.json.impl.provider.entity.JSONObjectProvider$App
      com.sun.jersey.json.impl.provider.entity.JSONRootElementProvider$App
      com.sun.jersey.json.impl.provider.entity.JSONListElementProvider$App
    */* -&gt;
      com.sun.jersey.core.impl.provider.entity.FormProvider
      com.sun.jersey.core.impl.provider.entity.StringProvider
      com.sun.jersey.core.impl.provider.entity.ByteArrayProvider
      com.sun.jersey.core.impl.provider.entity.FileProvider
      com.sun.jersey.core.impl.provider.entity.InputStreamProvider
      com.sun.jersey.core.impl.provider.entity.DataSourceProvider
      com.sun.jersey.core.impl.provider.entity.XMLJAXBElementProvider$General
      com.sun.jersey.core.impl.provider.entity.ReaderProvider
      com.sun.jersey.core.impl.provider.entity.DocumentProvider
      com.sun.jersey.core.impl.provider.entity.StreamingOutputProvider
      com.sun.jersey.core.impl.provider.entity.SourceProvider$SourceWriter
      com.sun.jersey.server.impl.template.ViewableMessageBodyWriter
      com.sun.jersey.json.impl.provider.entity.JSONJAXBElementProvider$General
      com.sun.jersey.json.impl.provider.entity.JSONArrayProvider$General
      com.sun.jersey.json.impl.provider.entity.JSONObjectProvider$General
      com.sun.jersey.core.impl.provider.entity.XMLRootElementProvider$General
      com.sun.jersey.core.impl.provider.entity.XMLListElementProvider$General
      com.sun.jersey.json.impl.provider.entity.JSONRootElementProvider$General
      com.sun.jersey.json.impl.provider.entity.JSONListElementProvider$General
     
    Mar 9, 2012 8:25:32 PM com.sun.jersey.spi.container.ContainerResponse logException
    SEVERE: Mapped exception to response: 500 (Internal Server Error)
    javax.ws.rs.WebApplicationException: com.sun.jersey.api.MessageException: A message body writer for Java class com.junctiontv.subm.model.Subscriber, and Java type class com.junctio
    ntv.subm.model.Subscriber, and MIME media type application/json was not found
            at com.sun.jersey.spi.container.ContainerResponse.write(ContainerResponse.java:285)
            at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1451)
            at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1363)
            at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1353)
            at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:414)
            at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:537)
            at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:708)
            at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
            at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
            at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
            at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:224)
            at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169)
            at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
            at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
            at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
            at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927)
            at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
            at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
            at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:987)
            at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:579)
            at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:307)
            at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
            at java.lang.Thread.run(Thread.java:619)
    Caused by: com.sun.jersey.api.MessageException: 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 was not found
            ... 24 more
    • Elad

      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

      • world_is_beautiful

        Thanks this solved my problem :-)

      • Thomas Fleming

        Spot on. Just what I was looking for.

  • san

    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

    • http://www.mkyong.com mkyong

      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.

      • Dharam

        Sorry i didn’t get. I am not using EJBs. I am using simple POJO.

  • Dharam

    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

    • Dharam

      Pls tell from post method point of view.

  • Navin

    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.

  • TestConfig

    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

  • TestConfig

    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.

    • http://www.mkyong.com mkyong

      Please provide your last caused by error message.

  • denu

    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:

    	@POST
    	@Path(&quot;setData&quot;)	
    	@Consumes(MediaType.APPLICATION_JSON)
    	public Response setData(List&lt;Map&lt;String,String&gt;&gt; data) {
     
    		String result = &quot;Track saved : &quot; + data;
    		return Response.status(201).entity(result).build();

    My jersey method isn’t fired. I got “HTTP ERROR: 415 Unsupported Media Type” in browser.

    What could be reason for this?

    • http://www.mkyong.com mkyong

      did you include “jersey-json.jar”? Look like your app server doesn’t support json as return type. Refer to your server documentation.

  • Martin

    Thanks buddy you saved my life with this post :))

  • Ibarra

    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

    • http://www.mkyong.com mkyong

      is “jersey-json” in your project classpath?

      • Ajay

        After adding jersey-json in class path still the same error occurs …..the error log is here

        SEVERE: Mapped exception to response: 500 (Internal Server Error)
        javax.ws.rs.WebApplicationException: com.sun.jersey.api.MessageException: A message body writer for Java class com.mkyong.Track, and Java type class com.mkyong.Track, and MIME media type application/json was not found
        at com.sun.jersey.spi.container.ContainerResponse.write(ContainerResponse.java:285)
        at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1437)
        at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1349)
        at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1339)
        at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:416)
        at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:537)
        at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:708)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:225)
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
        at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
        at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927)
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
        at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1001)
        at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:579)
        at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
        at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
        at java.lang.Thread.run(Unknown Source)
        Caused by: com.sun.jersey.api.MessageException: A message body writer for Java class com.mkyong.Track, and Java type class com.mkyong.Track, and MIME media type application/json was not found
        … 24 more

        • Ajay

          i have following jar in my lib folder

          asm-3.1.jar
          jackson-core-asl-1.9.9.jar
          jackson-jaxrs-1.9.9.jar
          jackson-mapper-asl-1.9.9.jar
          jackson-xc-1.9.9.jar
          jersey-client-1.9.jar
          jersey-core-1.9.1.jar
          jersey-json-1.13.jar
          jersey-server-1.9.1.jar
          jettison-1.3.2.jar
          jsr311-api-1.1.1.jar

          please suggest me if i am doing something wrong …….

          • Ajay

            Hello Mk yong ,
            Problem is Fixed with the jersey-bundle-1.8.jar file.

  • Pingback: RESTful Java client with Jersey client()