是否有必要包装一个支持对象?我想做这个:
@RequestMapping(value = "/Test", method = RequestMethod.POST)
@ResponseBody
public boolean getTest(@RequestBody String str1, @RequestBody String str2) {}
并使用这样的 JSON:
{
"str1": "test one",
"str2": "two test"
}
但是我必须使用:
@RequestMapping(value = "/Test", method = RequestMethod.POST)
@ResponseBody
public boolean getTest(@RequestBody Holder holder) {}
然后使用这个 JSON:
{
"holder": {
"str1": "test one",
"str2": "two test"
}
}
那是对的吗? My other option would be to change the RequestMethod
to GET
and use @RequestParam
in query string or use @PathVariable
with either RequestMethod
。
原文由 NimChimpsky 发布,翻译遵循 CC BY-SA 4.0 许可协议
你是对的,@RequestBody 注释参数应该包含请求的整个主体并绑定到一个对象,所以你基本上必须选择你的选项。
如果您绝对想要您的方法,那么您可以执行自定义实现:
说这是你的 json:
并且您想将其绑定到此处的两个参数:
首先定义一个自定义注解,比如
@JsonArg
,其中的 JSON 路径类似于您想要的信息的路径:现在编写一个自定义 HandlerMethodArgumentResolver ,它使用上面定义的 JsonPath 来解析实际参数:
现在只需使用 Spring MVC 注册它。有点复杂,但这应该可以正常工作。