Jae Carr
Jae Carr

Reputation: 1225

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?

Upvotes: 3

Views: 2008

Answers (1)

tim_yates
tim_yates

Reputation: 171054

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

Upvotes: 10

Related Questions