[英]Spring Bind @RequestBody to other data types
It is very common to see a JSON RequestBody being bind to POJO, like following: 看到一个JSON RequestBody绑定到POJO是很常见的,如下所示:
@RequestMapping(value="/users", headers="Accept=application/json",method=RequestMethod.POST)
public void create(@RequestBody CustomerInfo customerInfo){
...
}
Is it possible to have @RequestBody bind to non-POJO but other data types like primitive and non primitive data types? 是否可以将@RequestBody绑定到非POJO,但绑定到其他数据类型,例如原始和非原始数据类型?
EG: 例如:
@RequestMapping(value="/users", headers="Accept=application/json",method=RequestMethod.POST)
public void create(@RequestBody Set<Integer> ids){
...
}
Yes, it is possible. 对的,这是可能的。
Per your example, 根据您的示例,
public void create(@RequestBody Set<Integer> ids){
...
}
It will receive something like [1,2,3]
as the request body perfectly fine. 它会收到像[1,2,3]
类的东西,因为请求体非常好。
For another example for primitive, 再举一个原始的例子
public void create(@RequestBody int id) {
...
}
It will receive something like 1
as the request body perfectly fine. 作为请求主体,它将收到类似1
的信息。
However, for the latter example, I would not say it is application/json
. 但是,对于后一个示例,我不会说它是application/json
。
Per docs: 每个文档:
https://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-ann-requestbody https://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-ann-requestbody
You can use a Java Object to try as the type parameter of a @RequestBody
. 您可以使用Java对象尝试作为@RequestBody
的类型参数。 That said I don't think there is a support for primitives. 话虽如此,我认为没有对原语的支持。
Per docs you have this options: 根据文档,您可以选择以下选项:
The RequestMappingHandlerAdapter supports the @RequestBody annotation with the following default HttpMessageConverters: RequestMappingHandlerAdapter通过以下默认HttpMessageConverters支持@RequestBody批注:
- ByteArrayHttpMessageConverter converts byte arrays. ByteArrayHttpMessageConverter转换字节数组。
- StringHttpMessageConverter converts strings. StringHttpMessageConverter转换字符串。
- FormHttpMessageConverter converts form data to/from a MultiValueMap. FormHttpMessageConverter将表单数据与MultiValueMap之间进行转换。
- SourceHttpMessageConverter converts to/from a javax.xml.transform.Source. SourceHttpMessageConverter可与javax.xml.transform.Source之间进行转换。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.