Parsing json into java objects in spring-mvc
-
29-09-2019 - |
Question
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?
Solution
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).
OTHER TIPS
if you are using jquery on the client side, this worked for me:
Java:
@RequestMapping(value = "/ajax/search/sync")
public ModelAndView sync(@RequestBody SearchRequest json) {
Jquery (you need to include Douglas Crockford's json2.js to have the JSON.stringify function):
$.ajax({
type: "post",
url: "sync", //your valid url
contentType: "application/json", //this is required for spring 3 - ajax to work (at least for me)
data: JSON.stringify(jsonobject), //json object or array of json objects
success: function(result) {
//do nothing
},
error: function(){
alert('failure');
}
});