Saturday 5 September 2015

Return a Java object as JSON response from Spring MVC controller

To return an java object in JSON form from an spring objects requires two configurations:
1) Adding 'jackson-mapper-asl' dependency to the classpath
2) Add @ResponseBody annotation to the controller's method

Use in spring configuration file, to detect the spring annotations.


<mvc:annotation-driven />


1) Adding 'jackson-mapper-asl' dependency to the classpath
In a spring mvc project we need to add a 'jackson-mapper-asl' dependency to the pom.xml file, and object to json conversion is done bydefault.

<dependency>
       <groupId>org.codehaus.jackson</groupId>
       <artifactId>jackson-mapper-asl</artifactId>
       <version>1.9.10</version>
</dependency>

2) Add @ResponseBody annotation to the controller's method
Second thing we need to do is to use '@ResponseBody' annotation against the controller's method. 

This will make spring understand that method return value should be bound to the web response body.

If you annotate a method with @ResponseBody, spring will try to convert its return value and write it to the http response automatically. If you annotate a methods parameter with @RequestBody, spring will try to convert the content of the incoming request body to your parameter object on the fly.

package com.abusecore.controller;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.abusecore.model.Count;
import com.abusecore.services.IDataServices;

@Controller
@RequestMapping("/AbuseCore-1")
public class AbuseController {

       @Autowired
       IDataServices dataServices;
             
       /** Logger class to display logs. */
       static final Logger logger = Logger.getLogger(AbuseController.class);

       @RequestMapping(value="/count-tickets.json",method=RequestMethod.GET)
       public @ResponseBody Count getTicketsCount() {
              Count count = dataServices.getTicketsCount();
              logger.info("total tickets :" + count);
              return count;
       }
}

public @interface ResponseBody

Annotation that indicates a method return value should be bound to the web response body. Supported for annotated handler methods in Servlet environments.

As of version 4.0 this annotation can also be added on the type level in which case it is inherited and does not need to be added on the method level.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...