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.

1 Answer 1

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>
Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.