Spring 3 MVC and JSON example
In Spring 3, you can enable “mvc:annotation-driven” to support object conversion to/from JSON format, if Jackson JSON processor is existed on the project classpath.
In this tutorial, we show you how to output JSON data from Spring MVC.
Technologies used :
- Spring 3.0.5.RELEASE
- Jackson 1.7.1
- JDK 1.6
- Eclipse 3.6
- Maven 3
1. Project Dependencies
To use JSON in Spring MVC, you need to include Jackson dependency.
<properties> <spring.version>3.0.5.RELEASE</spring.version> </properties> <dependencies> <!-- Jackson JSON Mapper --> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.7.1</version> </dependency> <!-- Spring 3 dependencies --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> </dependencies>
2. Model
A simple POJO, later convert this object into JSON output.
package com.mkyong.common.model; public class Shop { String name; String staffName[]; //getter and setter methods }
3. Controller
Add “@ResponseBody” in the return value, no much detail in the Spring documentation.
As i know, when Spring see
- Jackson library existed on classpath
- “mvc:annotation-driven” is enabled
- Return method annotated with @ResponseBody
It will handle the JSON conversion automatically.
package com.mkyong.common.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.mkyong.common.model.Shop; @Controller @RequestMapping("/kfc/brands") public class JSONController { @RequestMapping(value="{name}", method = RequestMethod.GET) public @ResponseBody Shop getShopInJSON(@PathVariable String name) { Shop shop = new Shop(); shop.setName(name); shop.setStaffName(new String[]{"mkyong1", "mkyong2"}); return shop; } }
4. mvc:annotation-driven
Enable “mvc:annotation-driven” in your Spring configuration XML file.
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"> <context:component-scan base-package="com.mkyong.common.controller" /> <mvc:annotation-driven /> </beans>
5. Demo
URL : http://localhost:8080/SpringMVC/rest/kfc/brands/kfc-kampar

Download Source Code
Download it – SpringMVC-JSON-Example.zip (7 KB)
References
Tags : jackson json spring mvc spring3

The tutorial is very helpful and easy to follow, thank you.
Thanks a lot! Very clear and simple article.
Thanks for the simple and short tutorial. It helps a lot.
Thank you. Good work. Helped me learn fast.
make sure that you add two jackson related jar files.
jackson-core-asl-1.9.8.jar
jackson-mapper-asl-1.9.8.jar
@Ahmad, Apache Maven will just handle the dependencies correctly by adding the core required library.
hello,when i user ie open this, ie would make me downlaod.
It really helped me to configure json in spring 3.0. Big thanks to you from me :)
Hi
in Your source Exsample and your description,
there has not “/kfc/brands” folder. in that folder, what does it have?
so, I can not run your Example. You would like to show me, please
Hi, Im getting the below error when trying to do this(@ResponseBody),
com.ibm.ws.webcontainer.webapp.WebApp logServletError SRVE0293E: [Servlet Error]-[chpServlet]: com.ibm.ws.webcontainer.webapp.WebAppErrorReport: SRVE0295E: Error reported: 500
at com.ibm.ws.webcontainer.webapp.WebAppDispatcherContext.sendError(WebAppDispatcherContext.java:624)
at com.ibm.ws.webcontainer.webapp.WebAppDispatcherContext.sendError(WebAppDispatcherContext.java:642)
at com.ibm.ws.webcontainer.srt.SRTServletResponse.sendError(SRTServletResponse.java:1236)
at com.ibm.ws.webcontainer.srt.SRTServletResponse.sendError(SRTServletResponse.java:1210)
at org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver.handleHttpMessageNotWritable(DefaultHandlerExceptionResolver.java:344)
at org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver.doResolveException(DefaultHandlerExceptionResolver.java:131)
at org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver.resolveException(AbstractHandlerExceptionResolver.java:136)
at org.springframework.web.servlet.DispatcherServlet.processHandlerException(DispatcherServlet.java:1120)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:944)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:778)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:575)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:668)
at com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:1214)
at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:774)
at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:456)
at com.ibm.ws.webcontainer.servlet.ServletWrapperImpl.handleRequest(ServletWrapperImpl.java:178)
at com.ibm.ws.webcontainer.filter.WebAppFilterChain.invokeTarget(WebAppFilterChain.java:125)
at com.ibm.ws.webcontainer.filter.WebAppFilterChain.doFilter(WebAppFilterChain.java:77)
at com.ibm.ws.webcontainer.filter.WebAppFilterManager.doFilter(WebAppFilterManager.java:926)
at com.ibm.ws.webcontainer.filter.WebAppFilterManager.invokeFilters(WebAppFilterManager.java:1023)
at com.ibm.ws.webcontainer.servlet.CacheServletWrapper.handleRequest(CacheServletWrapper.java:87)
at com.ibm.ws.webcontainer.WebContainer.handleRequest(WebContainer.java:895)
at com.ibm.ws.webcontainer.WSWebContainer.handleRequest(WSWebContainer.java:1662)
at com.ibm.ws.webcontainer.channel.WCChannelLink.ready(WCChannelLink.java:195)
at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleDiscrimination(HttpInboundLink.java:452)
at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleNewRequest(HttpInboundLink.java:511)
at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.processRequest(HttpInboundLink.java:305)
at com.ibm.ws.http.channel.inbound.impl.HttpICLReadCallback.complete(HttpICLReadCallback.java:83)
at com.ibm.ws.tcp.channel.impl.AioReadCompletionListener.futureCompleted(AioReadCompletionListener.java:165)
at com.ibm.io.async.AbstractAsyncFuture.invokeCallback(AbstractAsyncFuture.java:217)
at com.ibm.io.async.AsyncChannelFuture.fireCompletionActions(AsyncChannelFuture.java:161)
at com.ibm.io.async.AsyncFuture.completed(AsyncFuture.java:138)
at com.ibm.io.async.ResultHandler.complete(ResultHandler.java:204)
at com.ibm.io.async.ResultHandler.runEventProcessingLoop(ResultHandler.java:775)
at com.ibm.io.async.ResultHandler$2.run(ResultHandler.java:905)
at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:1659)
Any inputs on this. Although this happens for one type of object only. Im running Spring 3.1.2 on WAS 8.
I now have exacltly the same problem, did you find any solution for your problem? Please help me.
Yeah I was able to figure that out. I had an empty class(that was JAXB Generated). It was causing the issue. Like, public class DataIndicator{}. There was no variable within it. I changed the schema(that was in my case). Check if you have a similar empty class(that is a part of the response object that ur trying to convert it to JSON). Hope this helps!!
simply rocks….mkyong
you should add “@ResponseBody” to the method …
Thanks for this post. I dont see an configuration which explicitly sets the response type to json. Is that something that happens by default. For example if i wanted to have an xml response type what would i need to do?
Thanks,
N
This is very nice website…
Very useful articles are posted here..
Thanks for you…
Would be nice if u can enhance the tutorial for WADL and some way of generating the code from the WADL like we could do using WSDL
I just hate REST because it got rid of the Service Definition part of SOAP for convenience.
I already have a PDF document generated by my backend, how do I return this in a RESTful service? What will the MarshallingView and ContentNegotiatingViewResolver look like?
thank you.
what about post how to get the json data post in the json format … please give an example
i am getting this error when running this example in browser. plz help
The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request “accept” headers ().
Hi,
You should in servlet.xml file and ensure the file should be error free.
add in servlet.xml
I get this same exact error in response. Status 406: “The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request “accept” headers ().”
I have exactly followed this procedure and also making sure my dependency for Jackson is set correctly. Here are more details if anyone has gotten this to resolve
http://stackoverflow.com/questions/12865093/spring-3-x-json-status-406-characteristics-not-acceptable-according-to-the-requ
Solution – This is a followup to the problem I had posted earlier which is now resolved. Hopefully this helps anybody else who might face this. The solution for the “406″ error in my case was to make the POJO getter methods public [I had them protected]
This might also be helpful for others.
http://stackoverflow.com/questions/4069903/spring-mvc-not-returning-json-content-error-406/12625196#12625196
That worked for me, Thanks a lot!!
Make sure you use Jackson 1.x, not 2.x
Hi,
How can I use MarshallingViewResolver to handle the conversion for json?
Could someone take me through it?
Thanks you. Very nice tutorial. This post has a huge value.
If one of the JSON name value pairs need to be made optional, what’s the best way to go about it ?
Eg. In this example String staffName[]; is optional…
Setup defaults in the constructor and got going :-)
Great example! Very helpful! Thanks!
A really good working example, thanks a lot :)
Unable to run this example. I downloaded all the dependencies. Still I’m getting error
No mapping found for HTTP request with URI [/JSONTest/rest/kfc/brands/Rani]
Missing:
———-
1) net.sf.sojo:sojo-optional:jar:0.5.0
Try downloading the file manually from the project website.
Then, install it using the command:
mvn install:install-file -DgroupId=net.sf.sojo -DartifactId=sojo-optional -Dversion=0.5.0 -Dpackaging=jar -Dfile=/path/to/file
Alternatively, if you host your own repository you can deploy the file there:
mvn deploy:deploy-file -DgroupId=net.sf.sojo -DartifactId=sojo-optional -Dversion=0.5.0 -Dpackaging=jar -Dfile=/path/to/file -Durl=[url] -DrepositoryId=[id]
Path to dependency:
1) SpringDemos:SpringDemos:jar:1.0
2) net.sf.spring-json:spring-json:jar:1.1
3) net.sf.sojo:sojo-optional:jar:0.5.0
———-
1 required artifact is missing.
for artifact:
SpringDemos:SpringDemos:jar:1.0
from the specified remote repositories:
central (http://repo1.maven.org/maven2)
Problem in downloading dependencies
I had to add the following jackson dependencies to get the downloaded example to work.
Hi
public ActionResult About()
{
List listStores = new List();
listStores = this.GetResults(“param”);
return Json(listStores, “Stores”, JsonRequestBehavior.AllowGet);
}
Using the above code i am able to get the below result :
[{"id":"1","name":"Store1","cust_name":"custname1","telephone":"1233455555","email":"abc@ac.com","geo":{"latitude":"12.9876","longitude":"122.376237"}},{"id":"2","name":"Store2","cust_name":"custname2","telephone":"1556454","email":"nfnf@ac.com","geo":{"latitude":"12.9876","longitude":"122.376237"}},
how would i able to get the result in below format ? would need stores at the beginning of the result.
{
"stores" : [
{"id":"1","name":"Store1","cust_name":"custname1","telephone":"1233455555","email":"abc@ac.com",
"geo":{"latitude":"12.9876","longitude":"122.376237"}},{"id":"2","name":"Store2","cust_name":"custname2","telephone":"1556454","email":"nfnf@ac.com","geo":{"latitude":"12.9876","longitude":"122.376237"}} ] }
Please help me in this regard.
If Mavan build doesn’t work replace the build tag with following one.
Use Maven 3.x
SpringMVC
maven-compiler-plugin
2.2
1.6
1.6
useful example
Thanks
Thanks!!!
This exactly what I need to build on..
Hello,
I am working on Spring MVC 3.0 JAXB & REST. I am new to these technologies. I am learning from your examples.
In the above examples I didn’t understand the URL format. Could you explain it. where was the “rest” configured (http://localhost:8080/SpringMVC/rest/kfc/brands/kfc-kampar)
I am getting 404 error when trying to execute this one in eclipse
SpringMVC is the webapp (directory name in the web server’s webapps directory)
In the webapp’s web.xml, the url mapping includes ‘rest’ as follows:
The controller takes you further in the url with the following annotation:
@RequestMapping(“kfc/brands”)
Whatever comes after that in the url is the ‘name’ PathVariable
I hosted his example in Tomcat and it works.
I discovered that the only misleading part in this example is the following in web.xml:
Since the servlet name, as defined in web.xml, is mvc-dispatcher, the default dispatcher servlet name is mvc-dispatcher-servlet.xml, which coincides with the given name in the web.xml
If you try to give any other name via this mechanism, the application will not work. You need to specify via servlet’s init-param as follows:
Thank you… very helpful.
Code snippet such as the following will allow UI to get to the controller:
$(document).ready(function() {
$.getJSON(“http://localhost:8080/SpringMVC/rest/kfc/brands/kfc-kampar”, function(shop) {
alert(shop.name);
});
});
When I run this example, its giving me Open/Save dialog on UI instead of printing JSOn data on browser.
How would I print on browser ? Do I need to set any Accept header ?
try this URL in Mozilla or Crome to get the output in browser
http://localhost:8080/SpringMVC/rest/kfc/brands/kfc-kampar.json
Hi,
I like your way of explaining things, all your helps are appreciated.
Can you please teach us how to interact from HTML (or jsp) to call an MVC controller , the controller will send data (as json)back to the page and update a div area.
Thanks lot.
Majid
Can you please post the reponse mapping code using json (I want to take json as an input to the spring controller and process the data)