hades
hades

Reputation: 4696

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?

E.G:

@RequestMapping(value="/users", headers="Accept=application/json",method=RequestMethod.POST)
public void create(@RequestBody Set<Integer> ids){
...
}

Upvotes: 1

Views: 3344

Answers (2)

Dante May Code
Dante May Code

Reputation: 11247

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.

Upvotes: 4

xiumeteo
xiumeteo

Reputation: 961

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.

Upvotes: 1

Related Questions