Spring 3 MVC and JSON example

In this tutorial, we show you how to output JSON data in Spring MVC framework.

Technologies used :

  1. Spring 3.2.2.RELEASE
  2. Jackson 1.9.10
  3. JDK 1.6
  4. Eclipse 3.6
  5. Maven 3

P.S In Spring 3, to output JSON data, just puts Jackson library in the project classpath.

1. Project Dependencies

Get Jackson and Spring dependencies.

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" 
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
        http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.mkyong.common</groupId>
	<artifactId>SpringMVC</artifactId>
	<packaging>war</packaging>
	<version>1.0-SNAPSHOT</version>
	<name>SpringMVC Json Webapp</name>
	<url>http://maven.apache.org</url>

	<properties>
		<spring.version>3.2.2.RELEASE</spring.version>
		<jackson.version>1.9.10</jackson.version>
		<jdk.version>1.6</jdk.version>
	</properties>

	<dependencies>

		<!-- 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>

		<!-- Jackson JSON Mapper -->
		<dependency>
			<groupId>org.codehaus.jackson</groupId>
			<artifactId>jackson-mapper-asl</artifactId>
			<version>${jackson.version}</version>
		</dependency>

	</dependencies>

	<build>
		<finalName>SpringMVC</finalName>
		<plugins>
		  <plugin>
			<groupId>org.apache.maven.plugins</groupId>
			<artifactId>maven-eclipse-plugin</artifactId>
			<version>2.9</version>
			<configuration>
				<downloadSources>true</downloadSources>
				<downloadJavadocs>false</downloadJavadocs>
				<wtpversion>2.0</wtpversion>
			</configuration>
		  </plugin>
		  <plugin>
			<groupId>org.apache.maven.plugins</groupId>
			<artifactId>maven-compiler-plugin</artifactId>
			<version>2.3.2</version>
			<configuration>
				<source>${jdk.version}</source>
				<target>${jdk.version}</target>
			</configuration>
		  </plugin>
		</plugins>
	</build>

</project>

2. Model

A simple POJO, later output this object as formatted JSON data.


package com.mkyong.common.model;

public class Shop {

	String name;
	String staffName[];

	//getter and setter methods
	
}

3. Controller

Add @ResponseBody as return value. Wen Spring sees

  1. Jackson library is existed in the project classpath
  2. The mvc:annotation-driven is enabled
  3. Return method annotated with @ResponseBody

Spring will handle the JSON conversion automatically.

JSONController.java

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.

mvc-dispatcher-servlet.xml

<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

spring mvc and json demo

Download Source Code

Download it – SpringMVC-Json-Example.zip (21 KB)

References

  1. mvc-annotation-driven documentation
  2. High-performance JSON processor
  3. Spring MVC and XML example

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
FOFANA Aly
Guest
FOFANA Aly

Hi!
I have some problem with jquery getJSON, can you help me?

nages
Guest
nages

We are using Jackson-2.9.4 version with spring version to 4.0.x RELEASE. But while formatting response in resttemplate is giving exception.
Please advise me what is the spring compatible version for jackson-2.9.4

curious
Guest
curious

Dear Sir,

Could you please help me with solving the following issue?

https://stackoverflow.com/questions/45477921/406-error-when-trying-to-parse-json-returned-from-spring-mvc-controller?noredirect=1#comment77928495_45477921

I have followed your tutorial for returning json from controller but itz simply not working. I am using JBOSS EAP server

curious
Guest
curious

Dear Sir,

Could you please help me with solving the following issue?

I have followed your tutorial for returning json from controller but itz simply not working. I am using JBOSS EAP server

Aleksei Mironov
Guest
Aleksei Mironov

IF DOESN’T WORK ?
!!!! ADD jackson dependency in pom.xml

com.fasterxml.jackson.core
jackson-databind
2.8.9

yugandhar
Guest
yugandhar

What is this following exception

excetion occured : org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation

abedeen
Guest
abedeen

not working ..

Alket
Guest
Alket

How can I run this project on Intellij IDEA with jdk 1.8 ?

sumit kumar
Guest
sumit kumar

Thanks for this post. its not working. i have download project. done maven clean install and deployed on Tomcat. when i hit the given url “http://localhost:8080/SpringMVC/rest/kfc/brands/kfc-kampar” getting Http-Status 404.
Need Help. Thanks in Advance.

Leaner
Guest
Leaner

org.apache.tomcat.maven
tomcat7-maven-plugin
2.2

http://localhost:8080/manager/text
TomcatServer

add this in pom.xml and build the maven like
eclipse run as>Maven build>under goals put “clean install tomcat7:run”

Er Vinayak Futak
Guest
Er Vinayak Futak

tell me the flow and i imported project but it is not running, tell me how to run it

Austin Poole
Guest
Austin Poole

Add this plugin in to your plugins inside of your pom.xml

org.apache.tomcat.maven
tomcat7-maven-plugin
2.1

/
8080
true

Also add this dependency in your pom file:

org.apache.tomcat.maven
tomcat7-maven-plugin
2.2

if you are using eclipse run as>Maven build>under goals put “clean install tomcat7:run” (without quotations”)

Then in your browser navigate to http://localhost:8080/rest/kfc/brands/kfc-kampar

Kedar Pagdhare
Guest
Kedar Pagdhare

Thanks

pranish
Guest
pranish

How does the application know that it has to return the value in JSON format

ankit
Guest
ankit

what if i am getting 404 error?

trackback
jQuery – Ajax request return 200 OK but error event is fired?

[…] Spring MVC and JSON […]

Deepak
Guest
Deepak

Thanks for this post. I have a doubt in configuring JSON Response prefix string. I have configured jsonPrefix in my project to prefix the response json with )]}’,n in MappingJson2HTTPMessageConverter class to fix common vulnerability. How could I see the response prefixed with the above string to confirm that this is working. I tried checking in chrome in the response string F12 -> Networks-> Json Response, however I could not find the string appended to the output. Could you please help me out with this?

dumkat
Guest
dumkat

When I have a field of type String with over 1000 characters, all the characters are turned into u0000. Any ideas?

Rajeev
Guest
Rajeev

Hi,

I am getting this error :

java.lang.IllegalArgumentException: No converter found for return value of type: class com.mkyong.common.model.Shop

on upgrading spring version to 4.2.0 RELEASE.

Julio Cesar Maciel
Guest
Julio Cesar Maciel

Thanks for this post!!
I have a question, how do you configure your project ?
Do you use only annotations setting the configuration into the code or do you prefer use the XML to set the configuration of frameworks like Spring mvc, spring batch or hibernate?

Thank you mkyong.

trackback
Spring 3 MVC hello world example – Annotation

[…] Spring 3 MVC and JSON example […]

trackback
Spring 3 MVC hello world example

[…] Spring 3 MVC and JSON example […]

AShk
Guest
AShk

P.S In Spring 3, to output JSON data, just puts Jackson library in the project classpath.

RJ
Guest
RJ

Whenever i am entering url,”http://localhost:8080/SpringMVC/rest/kfc/brands/kfc-kampar” in my web browser it show error page that “Resource is not available”. How can i solved it?

Ramesh Pabbati
Guest
Ramesh Pabbati

Here are couple of options
1. Try GET http://localhost:8080/kfc/brands/kfc-kampar and it should complete.

2. Change the URL mapping web.xml like this then GET http://localhost:8080/SpringMVC/rest/kfc/brands/kfc-kampar will work

mvc-dispatcher
/SpringMVC/rest/*

Salman
Guest
Salman

Why “rest” in URL what is represents?

http://localhost:8080/SpringMVC/rest/kfc/brands/test

nileshkhaire
Guest
nileshkhaire

Hi, what is the difference between ContentNegotiationManagerFactoryBean and ContentNegotiatingViewResolver ? We can also use ContentNegotiationManagerFactoryBean for the same purpose .

Mmde Git
Guest
Mmde Git

thanks mkyong for your wonderful tutorials, they are really helpful.
I have a small issue though, what should I do if the variable name is special to Java?
I am working with a bootstrap calendar (https://github.com/Serhioromano/bootstrap-calendar) that uses ‘class’ as one of JSON properties.

Mmde Git
Guest
Mmde Git

I’m back…
I needed to use jackson’s annotation @Jsonproperty(“class”) on the getter method.

CuriousUser
Guest
CuriousUser

Will the same work for jdk7 and spring 3.5?? Because I have created almost same project but its not working.I think there is some problem with jackson…I don’t think jackson 2.3 works with jdk7 correct me If I am wrong.

I am not getting any error message but the ‘alert’ in which I am displaying my data is not getting displayed. However If I just send a normal string instead of a complex object its works fine.

Can you please help?

Jose
Guest
Jose

Thanks a lot, all your post are great!!!!

karthik
Guest
karthik

Hi Eugen,

i added a sample project of Spring-boot with Jackson in “GIT hub Repository” .Here is the link to refer Sample Project https://github.com/karthikpamidimarri/sampleApp

For sql files here is the link http://pastebin.com/iRK7r2TL

karthik
Guest
karthik
Hi to all , I am new to Spring Boot ,i was face this problem of itteration but it’s resolved by using Jackson annotaions of @JsonBackReference and @JsonManagedReference and @JsonIdentityInfo after added these annotaions and bean configuration is everything fine .. but after i could not able to post the data as Json to a controller .Please suggest answer i am facing issue like 1)Requested URL is http://localhost:8080/custMast/state (POST) that time 405 method is coming and JSON is { “custmastCountry” : { “id” : 1, “name” : “INDIA”, “customerAddresses” : [ ] }, “name” : “MahaRashtra”, “createdOn” : null, “updatedOn”… Read more »
Johaness
Guest
Johaness

the tutorial of this guy never works as so easy.