3

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?

2
  • 1
    possible duplicate of Grails send request as JSON and parse it in controller Commented Oct 29, 2013 at 12:35
  • That particular question is trying to answer a very specific problem, I'm just asking for general example code because I can't seem to find any. I've read that answer before, a couple times... Commented Oct 29, 2013 at 12:42

1 Answer 1

11

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! Concise and to the point, just what I was looking for!
What if you want to get the value of "username" in this case. When I do it like this request.JSON.username I get [tim_yates]. That is with the brackets.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.