使用 Grails 在服务器端获取 JSON 数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3019838/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 17:30:42  来源:igfitidea点击:

Getting JSON data on server side with Grails

jsongrailsgroovy

提问by maximus

Once I post JSON data to a url in Grails, how can I get access to that data inside of the controller?

一旦我将 JSON 数据发布到 Grails 中的 url,我如何才能访问控制器内部的数据?

回答by Daniel Rinser

Grails automatically parses/unmarshals the JSON and you can access it via request.JSONin your controller. The object returned is of type JSONObjectand thus allows map-style access to the properties. You can also directly use this JSONObject for data binding:

Grails 会自动解析/解组 JSON,您可以通过request.JSON控制器访问它。返回的对象属于类型JSONObject,因此允许以地图方式访问属性。你也可以直接使用这个 JSONObject 进行数据绑定:

def jsonObject = request.JSON
def instance = new YourDomainClass(jsonObject)

回答by Mike Sickler

Check out the JSON classes in Grails:

查看 Grails 中的 JSON 类:

http://grails.org/doc/latest/api/org/codehaus/groovy/grails/web/json/package-frame.html

http://grails.org/doc/latest/api/org/codehaus/groovy/grails/web/json/package-frame.html

For example, here's how I iterate over a list of JSON records in a parameter called 'update':

例如,以下是我在名为“update”的参数中迭代 JSON 记录列表的方法:

    def updates = new org.codehaus.groovy.grails.web.json.JSONArray(params.updates)
    for (item in updates) {
                    def p = new Product()
        p.quantity = item.quantity
        p.amount = item.amount
        p = salesService.saveProductSales(p)

    }