I would like to use Spring's @RequestBody annotation to bind JSON from the request body to an object. Is it possible to use this in a Grails controller method? If not, is there a more elegant way other than using the request.JSON object which is created?
Here is what I'm trying to do:
FooController.groovy:
def someMethod(@RequestBody Bar bar) {
render(bar.baz)
}
class Bar {
String baz
}
I then POST the following JSON to this endpoint:
{
"baz":"chicken"
}
I would expect the response from the POST to be chicken.
Any idea if this is possible, or is there some other mechanism to bind JSON to a controller argument like this?
Thanks!
If you use resource or parseRequest in the relevant URL mapping (see http://grails.org/doc/latest/guide/webServices.html for details) then the incoming JSON will be parsed and used to fill the params map, i.e. the JSON
{
"baz":"chicken"
}
Will set params.baz == "chicken". The resulting params entries can then be bound into a command object in the usual way, you shouldn't need to annotate the action parameter.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With