Luc*_*ano 16 java rest spring-mvc spring-boot
我正在使用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"}'
Run Code Online (Sandbox Code Playgroud)
在我正在做的Spring控制器中:
public SomeResponseObject endpoint(
@RequestParam(value="arg1", required=true) String arg1,
@RequestParam(value="arg2", required=true) String arg2,
@RequestParam(value="json", required=true) Person person) {
...
}
Run Code Online (Sandbox Code Playgroud)
该json参数不会被序列化为Person对象.我得到了
400 error: the parameter json is not present.
Run Code Online (Sandbox Code Playgroud)
显然,我可以将json参数作为String并解析控制器方法中的有效负载,但这种方式无视使用Spring MVC.
如果我使用它,它都可以工作@RequestBody,但是我放弃了在JSON主体之外POST单独的参数的可能性.
Spring MVC中有没有办法"混合"普通的POST参数和JSON对象?
Mos*_*osd 21
是的,可以使用post方法发送params和body:示例服务器端:
@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;
}
Run Code Online (Sandbox Code Playgroud)
在您的客户端:
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"}'
Run Code Online (Sandbox Code Playgroud)
请享用
您可以通过使用自动连线将Converterfrom从注册为String参数类型来实现ObjectMapper:
import org.springframework.core.convert.converter.Converter;
@Component
public class PersonConverter implements Converter<String, Person> {
private final ObjectMapper objectMapper;
public PersonConverter (ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
}
@Override
public Date convert(String source) {
try {
return objectMapper.readValue(source, Person.class);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
36655 次 |
| 最近记录: |