Sunday, 22 May 2016

How to send JSON object as Response in Spring MVC

Add the below dependency in maven pom.xml

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

ObjectMapper  class helps to convert the object to json.

import org.codehaus.jackson.map.ObjectMapper;

@RequestMapping(value = "/<request_mapping_name>", method = RequestMethod.POST )
       public @ResponseBody String getMessage()  {
               List<String> errorList = new ArrayList();
               errorList.add("validation fails");

              ObjectMapper mapper  = new ObjectMapper();
               String json = null;
                            json =  mapper.writeValueAsString(errorList);
return json;
}
 

No comments:

Post a Comment