Spring MVC:是否可以返回Map< String,Object>使用Jackson动态转换为JSON? [英] Spring MVC: Is it possible to return a Map<String, Object> dynamically converted to JSON using Jackson?

查看:76
本文介绍了Spring MVC:是否可以返回Map< String,Object>使用Jackson动态转换为JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想让我的Spring MVC Web应用程序返回表示为JSON的模型状态。

I want to enable my Spring MVC web application to return models' state represented as JSON.

我意识到通过@ResponseBody注释控制器方法,你可以在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.

因此我想知道是否可以只填充一个地图(例如a HashMap),并由杰克逊序列化?我意识到我可以为包含状态的模型创建新的View类,但我宁愿不必这样做。

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.

谢谢。

推荐答案

我从几个控制器返回一个 Map< String,?> 和内容由Jackson自动转换为JSON - 正如您所说,当您还没有可以保存您希望返回的信息的域对象时,这样做会更容易。

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.

只要你的类路径中有jackson库,并且< mvc:annotation-driven /> in,就应该自动完成你的弹簧配置。我用于Jackson的maven依赖项:

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>

这篇关于Spring MVC:是否可以返回Map&lt; String,Object&gt;使用Jackson动态转换为JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆