我正在使用 Spring Boot(最新版本,1.3.6),我想创建一个 REST 端点,它接受一堆参数和一个 JSON 对象。像这样的东西:
curl -X POST http://localhost:8080/endpoint \
-d arg1=hello \
-d arg2=world \
-d json='{"name":"john", "lastNane":"doe"}'
在我目前正在做的 Spring Controller 中:
public SomeResponseObject endpoint(
@RequestParam(value="arg1", required=true) String arg1,
@RequestParam(value="arg2", required=true) String arg2,
@RequestParam(value="json", required=true) Person person) {
...
}
json
参数不会序列化为 Person 对象。
我得到一个
400 error: the parameter json is not present.
显然,我可以将 json
参数设置为字符串并在 Controller 方法中解析有效负载,但这违背了使用 Spring MVC 的要点。
如果我使用 @RequestBody
一切正常,但是我失去了在 JSON 主体之外发布单独参数的可能性。
在 Spring MVC 中有没有办法“混合”普通的 POST 参数和 JSON 对象?
最佳答案
是的,可以使用 post 方法同时发送参数和正文: 服务器端示例:
@RequestMapping(value ="test", method = RequestMethod.POST)
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public Person updatePerson(@RequestParam("arg1") String arg1,
@RequestParam("arg2") String arg2,
@RequestBody Person input) throws IOException {
System.out.println(arg1);
System.out.println(arg2);
input.setName("NewName");
return input;
}
在你的客户端上:
curl -H "Content-Type:application/json; charset=utf-8"
-X POST
'http://localhost:8080/smartface/api/email/test?arg1=ffdfa&arg2=test2'
-d '{"name":"me","lastName":"me last"}'
享受
关于java - 如何在 Spring MVC 中将 JSON 有效负载发布到 @RequestParam,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38262055/