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

时间:2010-06-11 02:28:42

标签: json grails groovy

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

2 个答案:

答案 0 :(得分:51)

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

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

答案 1 :(得分:6)

查看Grails中的JSON类:

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

例如,以下是我在一个名为'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)

    }