问题描述
我熟悉如何使用 @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必须在classpath中:
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
、或 @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 将无法帮助您处理它(请参阅 自定义 WebDataBinder 初始化).
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对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!