Last Updated: February 25, 2016
·
5.434K
· martypitt

Custom JSON views with Spring MVC and Jackson

Spring MVC provides amazing out-of-the-box support for returning your domain model in JSON, using Jackson under the covers.

However, often you may find that you want to return different views of the data, depending on the method that is invoked.

For example, a summary vs detail view on a complex object.

I've written a couple of classes that add support for Jackson's @JsonView into Spring MVC, allowing the view to be modified on a per-method basis.

Eg:

@Controller
public class BookService
{
    @RequestMapping("/books")
    @ResponseView(SummaryView.class)
    public @ResponseBody List<Book> getBookSummaries() {}

    @RequestMapping("/books/{bookId}")
    public @ResponseBody Book getBook(@PathVariable("bookId") Long BookId) {}
}

In this example, getBookSummaries() returns a summarized list of books, rather than the full set.

The full code is available over on my blog

1 Response
Add your response

wooooooow this very good idea ,and i have problem in it.
your address for code in not work plz give me your code if mybe
aa.azizkhani@gmail.com

over 1 year ago ·