问题描述
我熟悉如何使用 @ResponseBody
注释从我的 @Controller
方法返回json。
I'm familiar with how to return json from my @Controller
methods using the @ResponseBody
annotation.
现在我正在尝试将一些json参数读入我的控制器,但到目前为止还没有运气。
这是我的控制器的签名:
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) {
但是当我尝试调用此方法,spring抱怨:
无法将类型'java.lang.String'的值转换为必需类型'com.foo.SearchRequest'
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'
删除 @RequestBody
注释似乎没什么区别。
Removing the @RequestBody
annotation doesn't seem to make a difference.
手动解析json是有效的,所以Jackson必须在类路径中:
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?
推荐答案
你的参数应该是 @RequestParam
,或 a @RequestBody
,而不是两者。
Your parameter should either be a @RequestParam
, or a @RequestBody
, not both.
@RequestBody
用于POST和PUT请求,其中请求的主体是您想要的解析。 @RequestParam
用于指定参数,可以是URL,也可以是多部分表单提交。
@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.
所以你需要决定你需要哪一个。你真的想把你的JSON作为请求参数吗?这通常不是AJAX的工作原理,它通常作为请求体发送。
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.
尝试删除 @RequestParam
看看是否有效。如果没有,并且您真的将JSON作为请求参数发布,那么Spring将无法帮助您在没有额外管道的情况下处理它(请参阅)。
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).
这篇关于在spring-mvc中将json解析为java对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!