I'm familiar with how to return json from my @Controller
methods using the @ResponseBody
annotation.
Now I'm trying to read some json arguments into my controller, but haven't had luck so far. Here's my controller's signature:
@RequestMapping(value = "/ajax/search/sync") public ModelAndView sync(@RequestParam("json") @RequestBody SearchRequest json) {
But when I try to invoke this method, spring complains that: Failed to convert value of type 'java.lang.String' to required type 'com.foo.SearchRequest'
Removing the @RequestBody
annotation doesn't seem to make a difference.
Manually parsing the json works, so Jackson must be in the classpath:
// This works @RequestMapping(value = "/ajax/search/sync") public ModelAndView sync(@RequestParam("json") String json) { SearchRequest request; try { request = objectMapper.readValue(json, SearchRequest.class); } catch (IOException e) { throw new IllegalArgumentException("Couldn't parse json into a search request", e); }
Any ideas? Am I trying to do something that's not supported?
Either use an export mapping to create a JSON string that you can pass to the Java action and then create a JSON object again from that string or just pass a root object to the Java and then in Java retrieve all the attached objects over the references to that root object.
JSON Processing in Java : The Java API for JSON Processing JSON. simple is a simple Java library that allow parse, generate, transform, and query JSON.
Converting Java object to JSON In it, create an object of the POJO class, set required values to it using the setter methods. Instantiate the ObjectMapper class. Invoke the writeValueAsString() method by passing the above created POJO object. Retrieve and print the obtained JSON.
Your parameter should either be a @RequestParam
, or a @RequestBody
, not both.
@RequestBody
is for use with POST and PUT requests, where the body of the request is what you want to parse. @RequestParam
is for named parameters, either on the URL or as a multipart form submission.
So you need to decide which one you need. Do you really want to have your JSON as a request parameter? This isn't normally how AJAX works, it's normally sent as the request body.
Try removing the @RequestParam
and see if that works. If not, and you really are posting the JSON as a request parameter, then Spring won't help you process that without additional plumbing (see Customizing WebDataBinder initialization).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With