首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >JQuery、Spring MVC @RequestBody和JSON --让它协同工作

JQuery、Spring MVC @RequestBody和JSON --让它协同工作
EN

Stack Overflow用户
提问于 2011-05-06 16:00:37
回答 5查看 178.9K关注 0票数 70

我想有一个双向的JSON到Java序列化

我正在成功地使用 the Java to JSON to JQuery path...(@ResponseBody)例如

代码语言:javascript
复制
@RequestMapping(value={"/fooBar/{id}"}, method=RequestMethod.GET)
     public @ResponseBody FooBar getFooBar(
            @PathVariable String id,
            HttpServletResponse response , ModelMap model) {
        response.setContentType("application/json");
...
}

在JQuery中,我使用

代码语言:javascript
复制
$.getJSON('fooBar/1', function(data) {
    //do something
});

这对很有效(例如,注释已经可以工作了,这要感谢所有的答复者)

但是,如何实现反向路径:是否使用RequestBody将JSON序列化为Java对象?

无论我怎么尝试,我都不能让这样的东西工作:

代码语言:javascript
复制
@RequestMapping(value={"/fooBar/save"}, method=RequestMethod.POST)
public String saveFooBar(@RequestBody FooBar fooBar,
        HttpServletResponse response , ModelMap model) {

  //This method is never called. (it does when I remove the RequestBody...)
}

我正确地配置了Jackson (它会在输出时序列化),当然,我还将MVC设置为注解驱动

我该如何让它工作呢?这是完全可能的吗?或者Spring / JSON / JQuery是单向的?

更新:

我改变了杰克逊的设置

代码语言:javascript
复制
<bean id="jsonHttpMessageConverter"
    class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" />

<!-- Bind the return value of the Rest service to the ResponseBody. -->
<bean
    class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
    <property name="messageConverters">
        <util:list id="beanList">
            <ref bean="jsonHttpMessageConverter" />
<!--            <ref bean="xmlMessageConverter" /> -->              
        </util:list>
    </property>
</bean>

对(几乎相似的)建议

代码语言:javascript
复制
<bean id="jacksonMessageConverter"
    class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>
    <bean
        class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="messageConverters">
            <list>
                <ref bean="jacksonMessageConverter" />
            </list>
        </property>
    </bean> 

而且它似乎起作用了!我不知道到底是什么成功了,但它确实有效...

EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5908466

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档