JSON example with RESTEasy + Jackson

Jettison as JSON provider
You may also interest to read this RESTEasy + Jettison + JAXB example.

Many like Jackson JSON processor, and it supported in RESTEasy. In this tutorial, we show you how to convert an object to JSON format and return it back to the client.

1. RESTEasy + Jackson

To integrate Jackson with RESTEasy, you just need to include “resteasy-jackson-provider.jar“.

Note
When RESTEasy returned a json output, it will use Jackson provider to convert it automatically. You do not need to code a single line to integrate both.

File : pom.xml


  <repositories>
	<repository>
		<id>JBoss repository</id>
		<url>https://repository.jboss.org/nexus/content/groups/public-jboss/</url>
	</repository>
  </repositories>

  <dependencies>

	<dependency>
		<groupId>org.jboss.resteasy</groupId>
		<artifactId>resteasy-jaxrs</artifactId>
		<version>2.2.1.GA</version>
	</dependency>

	<dependency>
		<groupId>org.jboss.resteasy</groupId>
		<artifactId>resteasy-jackson-provider</artifactId>
		<version>2.2.1.GA</version>
	</dependency>

  </dependencies>

2. Simple Object

A simple object, later convert it into JSON format.


package com.mkyong.rest;

public class Product {

	String name;
	int qty;
	
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getQty() {
		return qty;
	}

	public void setQty(int qty) {
		this.qty = qty;
	}

}

3. JAX-RS

Annotate the method with @Produces("application/json"). RESTEasy will use Jackson provider to handle the JSON conversion automatically.


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.Response;

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

	@GET
	@Path("/get")
	@Produces("application/json")
	public Product getProductInJSON() {

		Product product = new Product();
		product.setName("iPad 3");
		product.setQty(999);
		
		return product; 

	}

	@POST
	@Path("/post")
	@Consumes("application/json")
	public Response createProductInJSON(Product product) {

		String result = "Product created : " + product;
		return Response.status(201).entity(result).build();
		
	}
	
}
Disabled RESTEasy auto scanning.
You must disabled the RESTEasy auto scanning, and register your REST service manually, otherwise, you will hits this error. Hope it get fix in future release.

File : web.xml


        <!-- disabled auto scan
        <context-param> 
             <param-name>resteasy.scan</param-name> 
             <param-value>true</param-value> 
	</context-param> -->

	<context-param>
		<param-name>resteasy.resources</param-name>
		<param-value>com.mkyong.rest.JSONService</param-value>
	</context-param>

4. Demo

See GET and POST method.

1. GET method
When URI pattern “/json/product/get” is requested, following JSON file will be returned.


{
	"qty":999,
	"name":"iPad 3"
}
jackson resteasy demo

2. POST method
You can “post” the json format string to URI pattern “/json/product/post“, it will convert into “Product” automatically.

Download Source Code

References

  1. Jackson Official Website
  2. JSON Support via Jackson

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

avatar
27 Comment threads
2 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
23 Comment authors
SivaJulianoWojtekparthDeme Carv Recent comment authors
newest oldest most voted
Deme Carv
Guest
Deme Carv

You said “You can “post” the json format string to URI pattern “/json/product/post“, it will convert into “Product” automatically”. Do you mean that if I open a Chrome without any plugin aimed for testing Rest Service like Postman it would work? At least, I tried http://localhost:8080/RESTfulExample/json/product/post? plus the line from your last image and it didn’t work. Please, correct me if I am wrong, as far as I know it is impossible to test a post to a rest web service straight from Browser unless you have some plugin installed. Note: I am prohibited to install plugins in Browser where… Read more »

Siva
Guest
Siva

How to create that URL for services, without URL i cannot able to run the project. Please help me with that

Juliano
Guest
Juliano

Hi, thanks for sharing the knowledge. You are well known in Brazil! I have a following doubt, do you have @Delet @Put examples? Thank you so much !!!

Wojtek
Guest
Wojtek

that’s the first site where all that stuff is explained in a simple and clean way, without relying on some specific tools etc. thank you!

parth
Guest
parth

by this @ character is getting converted into @ can you please help me on that.

Mihir
Guest
Mihir

can you please give a simple way as above if i don’t use maven and directly create dynamic web project in eclipse. As there is no pom.xml in my project i can not set the dependencies and the method doesn’t work for me… Please reply.

Serhii Solohub
Guest
Serhii Solohub

try just download jar files defined in pom.xml from maven repo and put them in libs folder

deepak
Guest
deepak

how to register other webservice in web.xml if i register in web.xml jboss 7 gives war failed error

jaybee
Guest
jaybee

I would really like to know how to get this running basiclly a reask of djangofan

djangofan
Guest
djangofan

Can you tell me how you start the web app to listen on port 8080? Where is the “RESTfulExample” uri defined? If I should run in Jetty, how do I generate the .war? Will this not work using Eclipses standard edition?

trackback
JAX-RS TUTORIALS | BUYWORKSELL

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

PRAVEEN REDDY
Guest
PRAVEEN REDDY

If i Commect the below piece of one line Code then only i can Able to Execute the Program.

//@Produces(“application/json”)

Please help me with out commenting the above line How can i Execute the Program’

Sudhir
Guest
Sudhir

I have written one rest webservice which consumes XML.
When my client invokes web service with a JSON as input it is returing an error “415 Unsupported Media Type”.

So here my question is how to return my cutome error meesage.

Thanks,
Sudhir

Developer
Guest
Developer

Get is working fine . But as soon as i try “post ” it gives me following error ..
SEVERE: Failed executing POST /product/post
org.jboss.resteasy.spi.UnsupportedMediaTypeException: Cannot consume content type
at org.jboss.resteasy.core.registry.Segment.match(Segment.java:117)
at org.jboss.resteasy.core.registry.SimpleSegment.matchSimple(SimpleSegment.java:33)
at org.jboss.resteasy.core.registry.RootSegment.matchChildren(RootSegment.java:327)
at org.jboss.resteasy.core.registry.SimpleSegment.matchSimple(SimpleSegment.java:44)
at org.jboss.resteasy.core.registry.RootSegment.matchChildren(RootSegment.java:327)
at org.jboss.resteasy.core.registry.RootSegment.matchRoot(RootSegment.java:374)
at org.jboss.resteasy.core.registry.RootSegment.matchRoot(RootSegment.java:367)
at org.jboss.resteasy.core.ResourceMethodRegistry.getResourceInvoker(ResourceMethodRegistry.java:350)
at org.jboss.resteasy.core.SynchronousDispatcher.getInvoker(SynchronousDispatcher.java:192)
at org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:125)
at org.jboss.resteasy.plugins.server.servlet.ServletContainerDispatcher.service(ServletContainerDispatcher.java:208)
at org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher.service(HttpServletDispatcher.java:55)
at org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher.service(HttpServletDispatcher.java:50)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
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:222)
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:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
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:1004)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:722)

Victor Costa
Guest
Victor Costa

If one uses resteasy 2.2.3 (or later), there’s no need to disable auto scan.

peace loh
Guest
peace loh

From your website, we are able to get the data from client side if the json return us the single record. How about the multiple records? Thanks.

Ajay
Guest
Ajay

Your Code have really helped me a lot to understand and implement code using Restful WebServices.

Could you help me with @PUT & @ Delete type service, how to build them and how to write client for them…

Thanks and Regards,
Ajay

Jaxer
Guest
Jaxer

Hi dude, thank you very much for this post, it helped me to save a lot of time.
I have a question for you: I’d like to create a javascript client, using jQuery for example, wich communicates with a server made like you explain here, how can I create automatically json strings on the client side wich can be translated by Jackson without problems? For example I’d like to have something to be used on the client side that permitt me to create a json string for a product who’s data are collected from a form.

Than you!

aa
Guest
aa

java.lang.LinkageError: loader constraint violation: when resolving field “DATETIME” the class loader (instance of org/jboss/classloader/spi/base/BaseClassLoader) of the referring class, javax/xml/datatype/DatatypeConstants, and the class loader (instance of ) for the field’s resolved type, javax/xml/namespace/QName, have different Class objects for that type
com.sun.xml.bind.v2.model.impl.RuntimeBuiltinLeafInfoImpl.(RuntimeBuiltinLeafInfoImpl.java:224)
com.sun.xml.bind.v2.model.impl.RuntimeTypeInfoSetImpl.(RuntimeTypeInfoSetImpl.java:61)
com.sun.xml.bind.v2.model.impl.RuntimeModelBuilder.createTypeInfoSet(RuntimeModelBuilder.java:129)
com.sun.xml.bind.v2.model.impl.RuntimeModelBuilder.createTypeInfoSet(RuntimeModelBuilder.java:81)
com.sun.xml.bind.v2.model.impl.ModelBuilder.(ModelBuilder.java:152)
com.sun.xml.bind.v2.model.impl.RuntimeModelBuilder.(RuntimeModelBuilder.java:89)
com.sun.xml.bind.v2.runtime.JAXBContextImpl.getTypeInfoSet(JAXBContextImpl.java:456)
com.sun.xml.bind.v2.runtime.JAXBContextImpl.(JAXBContextImpl.java:302)
com.sun.xml.bind.v2.runtime.JAXBContextImpl$JAXBContextBuilder.build(JAXBContextImpl.java:1136)
com.sun.xml.bind.v2.ContextFactory.createContext(ContextFactory.java:154)
com.sun.xml.bind.v2.ContextFactory.createContext(ContextFactory.java:121)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
java.lang.reflect.Method.invoke(Method.java:597)
javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:211)
javax.xml.bind.ContextFinder.find(ContextFinder.java:372)
javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:574)
javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:522)
org.jboss.resteasy.plugins.providers.jaxb.json.BadgerContext.(BadgerContext.java:22)
org.jboss.resteasy.plugins.providers.jaxb.json.JsonJAXBContextFinder.find(JsonJAXBContextFinder.java:97)
org.jboss.resteasy.plugins.providers.jaxb.json.JsonJAXBContextFinder.findCachedContext(JsonJAXBContextFinder.java:51)
org.jboss.resteasy.plugins.providers.jaxb.AbstractJAXBProvider.findJAXBContext(AbstractJAXBProvider.java:52)
org.jboss.resteasy.plugins.providers.jaxb.AbstractJAXBProvider.getMarshaller(AbstractJAXBProvider.java:143)
org.jboss.resteasy.plugins.providers.jaxb.AbstractJAXBProvider.writeTo(AbstractJAXBProvider.java:119)
org.jboss.resteasy.core.interception.MessageBodyWriterContextImpl.proceed(MessageBodyWriterContextImpl.java:117)
org.jboss.resteasy.plugins.interceptors.encoding.GZIPEncodingInterceptor.write(GZIPEncodingInterceptor.java:63)
org.jboss.resteasy.core.interception.MessageBodyWriterContextImpl.proceed(MessageBodyWriterContextImpl.java:123)
org.jboss.resteasy.core.ServerResponse.writeTo(ServerResponse.java:250)
org.jboss.resteasy.core.SynchronousDispatcher.writeJaxrsResponse(SynchronousDispatcher.java:579)
org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:500)
org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:119)
org.jboss.resteasy.plugins.server.servlet.ServletContainerDispatcher.service(ServletContainerDispatcher.java:208)
org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher.service(HttpServletDispatcher.java:55)
org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher.service(HttpServletDispatcher.java:50)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFilter.java:96)

XXl
Guest
XXl

Can you please explain your post method little bit more? I tried to execute it but couldn’t be successful.
Thanks for this amazing post

Billy
Guest
Billy

Please run the NetClientPost in the attached source codes.

yahoo_fellow
Guest
yahoo_fellow

I followed what u have mentioned in the tutorial, but facing

org.jboss.resteasy.core.NoMessageBodyWriterFoundFailure: Could not find MessageBodyWriter for response object of type: org.mgiver.vo.Task of media type: application/json

error. Please let me know how to resolve this.

Thanks,

Bateramos
Guest
Bateramos

Mannn… Thx very much!

trackback
jQuery ajax call to REST service | Easy jQuery | Free Popular Tips Tricks Plugins API Javascript and Themes

[…] I’m trying to make an ajax call from jquery to a rest service. The rest service used is right from a tutorial of mkyong’s blog, this one: http://www.mkyong.com/webservices/jax-rs/integrate-jackson-with-resteasy/ […]

trackback
RESTful Java client with RESTEasy client framework

[…] “GET” and “POST” requests to REST service that created in last “Jackson + JAX-RS” tutorial.1. RESTEasy Client FrameworkRESTEasy client framework is included in RESTEasy core […]

Provider
Guest
Provider

Thanks for the effort you took to expand upon this post.

trackback
RESTful Java client with Apache HttpClient

[…] a “GET” and “POST” request. Note The RESTful services from last “Jackson + JAX-RS” article will be reused.1. Get Apache HttpClientApache HttpClient is available in Maven […]

trackback
JAX-RS client with java.net.URL

[…] and good enough to perform basic operations for REST service.The RESTful services from last “Jackson + JAX-RS” article will be reused, and we will use “java.net.URL” and […]

trackback
Download JSON with RESTEasy + JAXB + Jettison

[…] format and return it back to client. Jackson as JSON provider You may also interest to read this RESTEasy + Jackson example.1. RESTEasy + JAXB + JettisonTo use JSON in RESTEasy, you need following dependencies. […]