7

I have a very simple question, but I can't seem to find a simple answer:

I got Jackson working to serialize Java beans to JSON in the response using @ResponseBody

But I didn't manage to serialize back JSON to Java beans in the request using @RequestBody

e.g.

// this works fine, Bean is being serialized to JSON 
@RequestMapping(...)
public @ResponseBody Bean getSomething(...){
    //...
}

// I don't know how to make this work, if if there is a way at all
@RequestMapping(...)
public void setSomething(@RequestBody Bean bean, ...){
    //...
}
  1. Is it possible for the request at all?
  2. If so, how to configure it?
  3. Is there a JQuery example / tips (e.g. setting the right content type)?

Update:

See JQuery, Spring MVC @RequestBody and JSON - making it work together some quirks in the configuration (it worked for ResponseBody, but didn't for RequestBody, which doesn't make sense, the configuration is either correct or wrong. could be a bug?)

Community
  • 1
  • 1
Eran Medan
  • 44,555
  • 61
  • 184
  • 276

1 Answers1

6
  1. Yes, it is possible.

  2. Your server side configuration is probably fine if your @ResponseBody is working.

  3. You will need to set the content-type to application/json. The JQuery.ajax() method has a contentType parameter. A great example/summary of AJAX and Spring 3 can be found here. Note that he is using a $.postJSON method, which is most likely this simple plugin.

David
  • 1,481
  • 11
  • 19
  • Thanks. This got me to some progress (the method is being called). However now I gey the object (bean) as null (although it's being sent correctly if tracing the HTTP), I'm close to giving up and serializing it using old school techniques... (just read that request to a String and use a JSON deserializer literally) – Eran Medan May 09 '11 at 02:27
  • Could it be my server is rejecting the application/json mime type??? could that be the sole reason? – Eran Medan May 09 '11 at 02:35
  • I would think you would get some HTTP error code, or some sort of of error you could see in the HTTP tracing. Is there a reason you can't use regular Spring binding and just pass in request parameters, instead of JSON? – David May 09 '11 at 02:56
  • Complex objects, that's the only reason... and consistency between input and output types. no HTTP errors – Eran Medan May 09 '11 at 20:47
  • Seems my configuration was good enough for ResponseBody but not for RequestBody, see this related question of mine: http://stackoverflow.com/questions/5908466/jquery-spring-mvc-requestbody-and-json-making-it-work-together – Eran Medan May 11 '11 at 02:37