In Spring REST JSON example, we will learn to write RESTful webservices capable of returning JSON representations of resources. We will use MappingJackson2JsonView to resolve views to JSON body.
Read More: Spring REST XML tutorial
1. Spring REST JSON – @ResponseBody Annotation
This first technique is simple and easy. We have to include only jackson dependencies into classpath of the application and spring will register Jackson2JsonMessageConverter
class automatically into context. Whenever we ask for a resource from REST API and provide http header “accept: application/json“, we will get back the json representation of resource.
1.1. Runtime JSON dependency
<!-- Jackson JSON Processor --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.4.1</version> </dependency>
1.2. @ResponseBody Support
Here @RestController = @Controller + @ResponseBody
@RestController public class EmployeeRESTController { @RequestMapping(value = "/employees") public EmployeeListVO getAllEmployees() { EmployeeListVO employees = new EmployeeListVO(); EmployeeVO empOne = new EmployeeVO(1,"Lokesh","Gupta","howtodoinjava@gmail.com"); EmployeeVO empTwo = new EmployeeVO(2,"Amit","Singhal","asinghal@yahoo.com"); EmployeeVO empThree = new EmployeeVO(3,"Kirti","Mishra","kmishra@gmail.com"); employees.getEmployees().add(empOne); employees.getEmployees().add(empTwo); employees.getEmployees().add(empThree); return employees; } @RequestMapping(value = "/employees/{id}") public ResponseEntity<EmployeeVO> getEmployeeById (@PathVariable("id") int id) { if (id <= 3) { EmployeeVO employee = new EmployeeVO(1,"Lokesh","Gupta","howtodoinjava@gmail.com"); return new ResponseEntity<EmployeeVO>(employee, HttpStatus.OK); } return new ResponseEntity(HttpStatus.NOT_FOUND); } }
2. Spring REST JSON – MappingJackson2JsonView Support
This is second technique. The MappingJackson2JsonView
class also depends on the presence of the Jackson JSON processor library in classpath, so you don’t need to add anything extra. Complete pom.xml
looks like this.
2.1. Maven dependencies
<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.howtodoinjava.demo</groupId> <artifactId>springrestexample</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>springrestexample Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <!-- Spring MVC support --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.1.4.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>4.1.4.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>4.1.4.RELEASE</version> </dependency> <!-- Jackson JSON Processor --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.4.1</version> </dependency> </dependencies> <build> <finalName>springrestexample</finalName> </build> </project>
2.2. Add MappingJackson2JsonView view
When you are using MappingJackson2JsonView
class, you will need to return a view name of type MappingJackson2JsonView
. So you will need to change two places.
2.2.1. Controller change
You will need to return viewName from controller method. In our case, view name is “jsonTemplate“.
package com.howtodoinjava.demo.controller; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import com.howtodoinjava.demo.model.EmployeeListVO; import com.howtodoinjava.demo.model.EmployeeVO; @Controller public class EmployeeRESTController { private EmployeeListVO getEmployeesCollection() { EmployeeListVO employees = new EmployeeListVO(); EmployeeVO empOne = new EmployeeVO(1,"Lokesh","Gupta","howtodoinjava@gmail.com"); EmployeeVO empTwo = new EmployeeVO(2,"Amit","Singhal","asinghal@yahoo.com"); EmployeeVO empThree = new EmployeeVO(3,"Kirti","Mishra","kmishra@gmail.com"); employees.getEmployees().add(empOne); employees.getEmployees().add(empTwo); employees.getEmployees().add(empThree); return employees; } @RequestMapping(value = "/employees") public String getAllEmployeesJSON(Model model) { model.addAttribute("employees", getEmployeesCollection()); return "jsonTemplate"; } }
2.2.2. Configuration Change
You will need to configure viewName “jsonTemplate” as bean of type MappingJackson2JsonView
. And you will need to configure view resolver of type BeanNameViewResolver
. This way viewName “jsonTemplate” will be matched with MappingJackson2JsonView
and parsed JSON response will be returned to client.
@Configuration public class RESTConfiguration { @Bean public View jsonTemplate() { MappingJackson2JsonView view = new MappingJackson2JsonView(); view.setPrettyPrint(true); return view; } @Bean public ViewResolver viewResolver() { return new BeanNameViewResolver(); } }
Equivalent XML configuration to above java configuration is as below.
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context/ http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc/ http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <context:component-scan base-package="com.howtodoinjava.demo" /> <mvc:annotation-driven /> <!-- JSON Support --> <bean name="viewResolver" class="org.springframework.web.servlet.view.BeanNameViewResolver"/> <bean name="jsonTemplate" class="org.springframework.web.servlet.view.json.MappingJackson2JsonView"/> </beans>
3. Spring REST JSON example – Demo
Now when you hit the URL : http://localhost:8080/springrestexample/employees
, you will get this result.

4. Spring REST JSON example – Project Structure

That’s all for this quick spring restful web services json example with spring mvc. Drop me your questions in comments.
Happy Learning !!
Akshay
I am getting response as string “jsonTemplate”
lalit
i am getting an error
The type org.springframework.context.annotation.ScopedProxyMode cannot be resolved. It is indirectly referenced from required .class files
Abhinay jain
My debugger is not coming from js file to java controller please help me
abhay
How can we show above employee response in html page?
sandeep
error:org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 9 in XML document from ServletContext resource [/WEB-INF/spring-servlet.xml] is invalid; nested exception is org.xml.sax.SAXParseException; lineNumber: 9; columnNumber: 69; cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element ‘context:component-scan’.
rajesh
Hi Lokesh
still i am getting the string “jsonTmeplate” instead of that json.
I am passing the json-value in header too.
Trupti
change your annotation from @RestController to @Controller it will work and add getter setter methods in EmployeeVo.java class
rajesh
I am still getting the output as jsontemplate instead of passing the json value in header.
Daal
Thanks for nice article. I am getting following error:
java.lang.NoSuchMethodError: org.springframework.web.servlet.view.json.MappingJackson2JsonView.setResponseContentType(Ljavax/servlet/http/HttpServletRequest;Ljavax/servlet/http/HttpServletResponse;)V
Can you please help.
Entries in classpath file
Shashi Shekhar
Hi Lokesh,
when i try sending json as data in ajax call to spring request handler method it says “Request method ‘POST’ not supported” even though I have mentioned method type POST in server side as well as client side ajax call.
it is a liferay environment and springframework. But same code is working on a separate spring app. I am not able to figure out what could be the problem.
Can this problem be because of jackson-databinding jar version. If yes how could i know which version should i use with spring 4.1.4
Lokesh Gupta
Doesn’t sound version issue to me. It’s probably
@RequestMapping
issue. Try appending or removing “/”. Otherwise please share the method signature you are using.Shashi Shekhar
@RequestMapping(value = “/coa/listtype/calculator”, produces = “application/json;charset=UTF-8″, consumes=”application/json;charset=UTF-8”, method = RequestMethod.POST)
public @ResponseBody String saveListCalcExpense(@RequestBody ListTypeCalculator listTypeCalculator){
Result result;
try{
System.out.println(“DamageId >>>>>>>>>>”+listTypeCalculator.getDamageId());
result = new Result(ResultStatus.SUCCESS, “save_calc_expense”, listTypeCalculator);
}catch(Exception e){
result = new Result(ResultStatus.ERROR, “save_calc_expense”, null);
}
return new Gson().toJson(result);
}
Shashi Shekhar
It is also saying browser console “NetworkError: 405 Method Not Allowed” and on server side it is saying “WARN org.springframework.web.servlet.PageNotFound::handleHttpRequestMethodNotSupported – Request method ‘POST’ not supported”
Lokesh Gupta
It’s probably
@requestmapping
issue. Try removing “/” fromvalue = “/coa/listtype/calculator”
. Make itvalue = “coa/listtype/calculator”
. Use consumes and produces=MediaType.APPLICATION_JSON_VALUE instead ofapplication/json;charset=UTF-8
.Shashi Shekhar
Even consumes and produces=MediaType.APPLICATION_JSON_VALUE didn’t work… 🙁 … I also tried removing “/” but didn’t the things working… same code is working on a separate project i have created just to test this. But didn’t get any breakthrough on the main project.
Earlier I was using following jars
org.codehaus.jackson
jackson-core-asl
1.9.13
org.codehaus.jackson
jackson-jaxrs
1.9.13
org.codehaus.jackson
jackson-mapper-asl
1.9.13
Now I changed it to
com.fasterxml.jackson.core
jackson-databind
2.4.1.3
com.fasterxml.jackson.core
jackson-annotations
2.4.1
Still having same issue.
Ajai
Are u having jackson 2.1.2 in your lib
Partha Sarkar
Look at the xml returned by the web service it is employees under employees . is it right. how should I changed it ?
Lokesh Gupta
Try changing JAXB annotations in Employees.java class.
Gaurav
Hi,
Used first approach but getting an below error. Could you please tell me that why I am getting this error.
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException
Thanks,
Gaurav
Nash
thanks for tutorial. In above condition, in my case “jsonTemplate” is behaving like string even after the execution. My output is string “jsonTemplate” althought I think i have correctly configured Mappingjackson2Jasonview and BeanNameViewResolver. Could you please let me know what might be the possible cause for “jsonTemplate” not connecting to Mappingjackson2jasonview.
Lokesh Gupta
Are you passing “accept: application/json” HTTP header?
Smail
Hi,
We can just use
@RequestMapping(value = “/employees”, method = RequestMethod.GET ,produces=MediaType.APPLICATION_JSON_VALUE) without change compared to Spring REST XML tutorial
rinilnath
The resultant is invalid format of JSON. Not the one as shown in the image.
So in chrome it shows only word jsonTemplate
Lokesh Gupta
If you will configure the project with information present in this post, you will get similar response.
Chirag
Same here. It shows only word jsonTemplate
Sharat
Getting JSon response with empty values. Sample attached:
{“employees”:{“employees”:[{},{},{}]}}
Lokesh Gupta
Is your EmployeeVO class different ??
Kartik
Yes, Getting the same response.
Kartik
{“employees”:{“employees”:[{},{},{}]}}
Lokesh Gupta
Make sure you are returning some data first. and have proper setter and getter methods as well.
Kartik
I have implemented same class which you have given in https://howtodoinjava.com/spring-rest/spring-rest-hello-world-xml-example/
Kartik
Done..Getter setter were missing.
Lokesh Gupta
Great !!
Binh Thanh Nguyen
Thanks, nice share