0

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.

skaffman
  • 398,947
  • 96
  • 818
  • 769
bisgardo
  • 4,130
  • 4
  • 29
  • 38

1 Answers1

4

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:

    <dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-mapper-asl</artifactId>
        <version>1.8.5</version>
        <scope>runtime</scope>
    </dependency>
John Farrelly
  • 7,289
  • 9
  • 42
  • 52
  • Correct. One minor addition: you can also consider using `JsonNode` as the type; this represents a JSON tree, and is often more convenient to handle (traverse, modify) than Maps as one can omit null checks, casts; but still need not create matching POJOs. – StaxMan Apr 23 '12 at 22:21