Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Example code for having a Grails Controller deal with a JSON request

I have been up and down the internet but I am having a devil of a time finding some simple sample code for making Grails process a JSON request.

Basically all I want is for someone to send me a JSON file and for me to be able to pass it to one of my business/domain classes to be worked with. The JSON file can either come in as a simple text string or attached to a request object. Just so long as I can pull the JSON out and parse it I suppose it doesn't matter.

I apologize, I'm a bit of a noob and I know the request is vague. But is there a kind soul out there that can give me some example code to work with? Just an example that shows how Grails should be used when receiving JSON request?

like image 543
Jay Carr Avatar asked Jan 26 '26 01:01

Jay Carr


1 Answers

You should be able to have a controller method like:

def parse() { 
    println request.JSON
    def answer = [ status: 'ok' ]
    render answer as JSON
}

Then calling that from the command line (assuming it's in an application called json and a controller called JsonRecieverController):

curl -X POST \
     -H 'Content-Type: application/json' \
     -d '{ "username": "tim_yates", "answer": "true" }' \
     http://localhost:8080/json/jsonReciever/parse

Will print the JsonObject:

[username:tim_yates, answer:true]

And return

{"status":"ok"}

To curl

like image 68
tim_yates Avatar answered Jan 27 '26 13:01

tim_yates



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!