简体   繁体   中英

Spring Bind @RequestBody to other data types

It is very common to see a JSON RequestBody being bind to POJO, like following:

@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?

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.

For another example for primitive,

public void create(@RequestBody int id) {
    ...
}

It will receive something like 1 as the request body perfectly fine.

However, for the latter example, I would not say it is application/json .

Per docs:

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 . 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:

  • ByteArrayHttpMessageConverter converts byte arrays.
  • StringHttpMessageConverter converts strings.
  • FormHttpMessageConverter converts form data to/from a MultiValueMap.
  • SourceHttpMessageConverter converts to/from a javax.xml.transform.Source.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM