开发者

Spring3 REST Web Services with Jackson JSONViews

开发者 https://www.devze.com 2023-02-12 17:55 出处:网络
I got a plain spring3 web project set up and have a controller method like this: @RequestMapping(method = RequestMethod.GET, value = \"/book/{id}\", headers = \"Accept=application/json,application/xm

I got a plain spring3 web project set up and have a controller method like this:

@RequestMapping(method = RequestMethod.GET, value = "/book/{id}", headers = "Accept=application/json,application/xml")
public @ResponseBody
Book getBook(@PathVariable final String id)
{
    logger.warn("id=" + id);
    return new Book("12345", new Date(), "Sven Haiges");
}

It returns a new book object which will be transformed to JSON or XML because of the transformers I setup in the spring config:

<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
    <property name="messageConverters">
        <list>
            <ref bean="jsonConverter" />
            <ref bean="marshallingConverter" />
        </list>
    </property>
</bean>

JSON generation (and XML) all works, but I would like to be able to define multiple views for the data. For example I'd like to specify a detailed view with less properties in the exposed JSON/XML and a detailed view with the full set of properties.

Using Jackson's ObjectMapper this is possible like this:

objectMapper.writeValueUsingView(out, beanInstance, ViewsPublic.class);

Is there a way I can configure Spring to use a s开发者_Python百科pecific VIEW (detailed/summary)? The only way to achieve this right now is to use different DTOs returned from my controller methods.

Thanx!


If you need that level of control, then you need to do it yourself.

So rather than using @ResponseBody, instead use your own ObjectMapper to write the response manually, e.g.

private final ObjectMapper objectMapper = new ObjectMapper();

@RequestMapping(method = RequestMethod.GET, value = "/book/{id}", headers = "Accept=application/json,application/xml")
public void getBook(@PathVariable final String id, HttpServletResponse httpResponse)
{
    logger.warn("id=" + id);
    Book book = new Book("12345", new Date(), "Sven Haiges");
    objectMapper.writeValueUsingView(httpResponse.getWriter(), book, ViewsPublic.class);
}

By the way, writeValueUsingView is deprecated in the current version of JSON (see javadoc).

0

精彩评论

暂无评论...
验证码 换一张
取 消