Getting JSON data on server side with Grails

25,043

Solution 1

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

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

Solution 2

Check out the JSON classes in Grails:

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':

    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)

    }
Share:
25,043
maximus
Author by

maximus

Freelance Python/Javascript web developer. Geek, and general smart-ass.

Updated on June 14, 2020

Comments

  • maximus
    maximus almost 4 years

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