我想有一個雙向的JSON到Java序列化了jQuery,Spring MVC的@RequestBody和JSON - 使它共同努力
我使用成功的Java來JSON jQuery的路徑...(@ResponseBody
) 例如
@RequestMapping(value={"/fooBar/{id}"}, method=RequestMethod.GET)
public @ResponseBody FooBar getFooBar(
@PathVariable String id,
HttpServletResponse response , ModelMap model) {
response.setContentType("application/json");
...
}
和jQuery中我使用
$.getJSON('fooBar/1', function(data) {
//do something
});
這個作品以及(如註釋已經工作,感謝所有的應答者)
但是,我怎麼做反向路徑:使用RequestBody將JSON序列化爲Java對象?
不管我怎麼努力,我不能讓這樣的事情的工作:
@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...)
}
我有傑克遜正確配置(它系列化的出路),我有MVC設置爲驅動的註解當然
我該如何使它工作?有沒有可能?或者是Spring/JSON/JQuery是單向的(out)?
更新:
我改變了這個傑克遜設置
<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>
到了(幾乎similiar一個)建議
<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>
它似乎工作!我不知道這個訣竅究竟是什麼,但它的工作原理是......
我在這裏更好地解釋了這個問題:http://stackoverflow.com/questions/5930894/can-jackson-be-used-with-spring-mvc-3-0-to-also-bind-the-requestbody- (我會關閉這個,因爲它似乎太長,不清楚) – 2011-05-08 23:02:14
它看起來沒有被調用,因爲你正在做一個GET,但你的方法是一個POST。 – egervari 2013-09-29 18:24:06