Spring MVC - Forced controller to create MappingJacksonJsonView (s)

Here we have a basic webapp using JSP that should provide multiple JSON-based REST service URLs.

These URLs will be under /services and will be generated using MyRestServicesController .

In the examples I see for JSON-based settings, everyone uses a ContentNegotiatingViewResolver . But for me this seems redundant, as this resolver seems to be for situations where the same URL can produce a different result.

I just want my RestServicesController always create MappingJacksonJsonView(s) .

Is there a cleaner, more direct way to just direct the controller to do this?

+8
java spring-mvc
source share
3 answers

Is there a cleaner, more direct way to just direct the controller to do this?

Yes there is. You can see this sample that I posted in the Spring forums . In short, I prefer to do this through the following.

ApplicationContext:

 <!-- json view, capable of converting any POJO to json format --> <bean id="jsonView" class="org.springframework.web.servlet.view.json.MappingJacksonJsonView"/> 

controller

 @RequestMapping("/service") public ModelAndView getResultAsJson() { Object jsonObj = // the java object which we want to convert to json return new ModelAndView("jsonView", "result", jsonObj); } 

EDIT 2013: These days, the @skaffman approach would be a good alternative.

+12
source share

If all you have to do is output JSON, then the view layer itself is redundant. You can use the @ResponseBody annotation to instruct Spring to serialize your model directly using Jackson. It requires less configuration than the MappingJacksonJsonView approach, and the code is less cluttered.

+9
source share

While you are using mvc: annotation-driven , and Jackson is in the classpath, then all you have to do is use @ResponseBody on your methods, and the return type will be converted to JSON for Spring's standard HTTP message conversion function .

Also watch this video at approximately 37:00: Mastering Spring MVC .

+3
source share

All Articles