JQuery, Spring MVC @RequestBody и JSON - совместная работа

I would like to have a bidirectional JSON to Java serialization

I'm using successfully the Java to JSON to JQuery path... (@ResponseBody) e.g.

@RequestMapping(value={"/fooBar/{id}"}, method=RequestMethod.GET)
     public @ResponseBody FooBar getFooBar(
            @PathVariable String id,
            HttpServletResponse response , ModelMap model) {
        response.setContentType("application/json");
...
}

and In JQuery I use

$.getJSON('fooBar/1', function(data) {
    //do something
});

this works well (e.g. annotations work already, thanks to all the answerers)

However, how do I do the reverse path: have JSON be serialized to a Java Object back using RequestBody?

no matter what I try, I can't get something like this to work:

@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...)
}

I have Jackson configured correctly (it serializes on the way out) and I have MVC set as annotations driven of course

How do I make it work? is it possible at all? or is Spring / JSON / JQuery is oneway (out)?


Update:

I changed this Jackson setting

<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>

To the (almost similiar one) suggested

<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> 

And it seems to work! I don't know what exactly did the trick, but it works...

70
задан Eran Medan 11 May 2011 в 02:34
поделиться