Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
398 views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...