Monday, 29 October 2012

Returning a JSON in Spring (With Annotations)

This post provides the simplest example to return a JSON from a Spring controller. It is based on the Spring MVC With Annotations example. The code is available on GitHub in the Spring-Returning-A-JSON directory.

For a full Spring MVC REST calls with Ajax example, see here.


On top of current dependencies, we add the Jackson mapper dependency:
This dependency enables the conversion of Java objects into a JSON representation.


For this example, we use a simple SomeData class:
public class SomeData {

    private String name;
    private long time;

    public SomeData(String name, long time) { = name;
        this.time = time;

    public SomeData() {
        name = "";
        time = System.currentTimeMillis();

    // Setters & Getters



We modify our controller as following:
public class MyController {

    @RequestMapping(value = "/")
    public String home() {
        return "index";

    @RequestMapping(value="/getJSON/{name}", method = RequestMethod.GET)
    public @ResponseBody SomeData getJSON(@PathVariable String name) {

        SomeData result
            = new SomeData(name, System.currentTimeMillis());

        return result;


The getJSON() method has special annotations usage:
  • @RequestMapping's value contains {name} which will be extracted by Spring an inserted as the parameter value in the method.
  • @ResponseBody's indicates that the body of the response to the user's request must be filled with what is returned by the method. Here, we return a SomeData object. Since we have added the Jackson dependency, Spring will automatically detect it and perform the conversion of this object into its JSON representation.
  • @PathVariable extracts the parameter's name from the URL's {name} and sets its as the parameter value in the getJSON() method.

JSP Index Page

Our index page remains very simple:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="" %>
<!doctype html>
<html lang="en">
    <meta charset="utf-8">
    <title>Welcome !!!</title>
    Welcome To Spring Returning A JSON !!!
    <a href="<c:url value='/getJSON/Arthur'/>">Get JSON for Arthur !!!</a>
It contains a link making a call to /getJSON/Arthur.

Running The Example

Once compiled, the example can be run with mvn tomcat:run. Then, browse:


The home page will display:

Click on the link to retrieve the JSON:

More Spring related posts here.