I want to enable my Spring MVC web application to return models’ state represented as JSON.
I realize that by annotating the controller method by @ResponseBody, you can convert between JSON and objects of a corresponding type. However, the model object that I want to view speaks directly to a database without maintaining any state itself.
I therefore wonder if I could instead just populate a Map (e.g. a HashMap), and have that serialized by Jackson? I realize that I could make new View classes for my models containing the state, but I would rather not have to do that.
Thanks.
I return a
Map<String, ?>from several of my controllers, and the content is converted automatically to JSON by Jackson – as you say, it is easier to do it this way when you don’t already have a domain object that can hold the information you wish to return.This should be done automatically for you as long as you have the jackson libraries in your classpath, and have
<mvc:annotation-driven/>in your spring configuration. The maven dependencies I use for Jackson: