我正在使用JSON (最新版本,1.3.6),我想创建一个JSON端点,它接受一堆参数和一个JSON。类似于:
curl -X POST http://localhost:8080/endpoint \
-d arg1=hello \
-d arg2=world \
-d json='{"name":"john", "lastNane":"doe"}'
在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) {
...
}
json
参数不会被序列化为Person对象。我得到了一个
400 error: the parameter json is not present.
显然,我可以将json
参数设置为字符串并解析控制器方法中的有效负载,但这有点违背了使用Spring MVC的意义。
如果我使用@RequestBody
就可以了,但是之后我就不可能在JSON主体之外发布单独的参数了。
在Spring MVC中有没有办法“混合”正常的POST参数和对象?
发布于 2016-07-08 18:07:58
可以,可以使用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;
}
在你的客户端上:
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"}'
尽情享受
发布于 2018-05-29 06:59:06
为此,可以使用自动连接的Converter
将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 Person convert(String source) {
try {
return objectMapper.readValue(source, Person.class);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
发布于 2019-07-15 19:37:27
您可以使用RequestEntity。
public Person getPerson(RequestEntity<Person> requestEntity) {
return requestEntity.getBody();
}
https://stackoverflow.com/questions/38262055
复制相似问题