Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use Spring's @RequestBody in a Grails action?


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!

like image 201
Polaris878 Avatar asked Jan 26 '26 14:01

Polaris878


1 Answers

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.

like image 194
Ian Roberts Avatar answered Jan 28 '26 05:01

Ian Roberts



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!