简体   繁体   English

让Grails Controller处理JSON请求的示例代码

[英]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. 我一直在互联网上,但我有一个时间找到一些简单的示例代码,使Grails处理JSON请求。

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. 基本上我只想要有人给我发送一个JSON文件,并且让我能够将它传递给我的一个业务/域类来使用。 The JSON file can either come in as a simple text string or attached to a request object. JSON文件可以作为简单文本字符串输入或附加到请求对象。 Just so long as I can pull the JSON out and parse it I suppose it doesn't matter. 只要我能把JSON拉出并解析它,我想它没关系。

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? 举个例子来说明在接收JSON请求时应该如何使用Grails?

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 ): 然后从命令行调用它(假设它在一个名为json的应用程序和一个名为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 : 将打印JsonObject

[username:tim_yates, answer:true]

And return 并返回

{"status":"ok"}

To curl curl

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM