我想实现一个web服务,它在request-payload中只使用一个命名参数。在curl视图中它应该像: curl -X PATCH myurl.net/my_service -d“{mySingleParameter:49}”
我正在尝试使用Spring,但我想知道要将此类有效负载映射到我的方法,我必须声明一个新类。像:
...
public static class PayloadWithSingleParamMSP{
public Long mySingleParameter;
}
@RequestMapping(value = "my_service", method = RequestMethod.PATCH)
public String myService(@RequestBody PayloadWithSingleParamMSP payload){
Long valueWhichIReallyNeed = payload.mySingleParameter;
//do job
...
}
...
但有没有办法直接获取我真正需要的价值(mySingleParameter)?
答案 0 :(得分:3)
你有几个选择:
@RequestMapping(value = "my_service", method = RequestMethod.PATCH)
public String myService(@RequestBody ObjectNode payload){
Long valueWhichIReallyNeed = payload.get("mySingleParameter").asLong();
//do job
...
}
或
@RequestMapping(value = "my_service", method = RequestMethod.PATCH)
public String myService(@RequestBody Map<String, String> payload){
Long valueWhichIReallyNeed = Long.parseLong(payload.get("mySingleParameter"));
//do job
...
}
甚至
@RequestMapping(value = "my_service", method = RequestMethod.PATCH)
public String myService(@RequestBody Long mySingleParameter){
Long valueWhichIReallyNeed = mySingleParameter;
//do job
// ...
}
但在最后一种情况下,您的卷曲将如下所示:
curl -X PATCH myurl.net/my_service -d "49"
在此问题的答案中,您可以找到更多选项:Passing multiple variables in @RequestBody to a Spring MVC controller using Ajax