Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring MVC - Force a controller to produce MappingJacksonJsonView(s)

Here we have a basic webapp using JSP which needs to provide a few JSON based REST service URLs.

These urls will all reside under /services and be generated by a MyRestServicesController.

The examples I see for settings up JSON based views all use ContentNegotiatingViewResolver. But it seems like overkill to me as this resolver seems meant for situations where the same URL might produce different output.

I just want my one RestServicesController to always produce MappingJacksonJsonView(s).

Is there a cleaner, more straight forward way to simply direct the controller to do this?

like image 668
David Parks Avatar asked Mar 21 '11 07:03

David Parks


2 Answers

Is there a cleaner, more straight forward way to simply direct the controller to do this?

Yes there is. You can have a look at this sample I posted in Spring forums. In short the way I prefer to do it is 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: In these modern days, @skaffman's approach would be a nice alternative.

like image 195
Johan Sjöberg Avatar answered Oct 11 '22 21:10

Johan Sjöberg


If all you need 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.

like image 43
skaffman Avatar answered Oct 11 '22 21:10

skaffman