28

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

maximus
  • 2,417
  • 5
  • 40
  • 56

2 Answers2

51

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)
Daniel Rinser
  • 8,855
  • 4
  • 41
  • 39
  • could you explain what am I missing with the same approach (http://stackoverflow.com/questions/15067379/grails-initiating-domain-class-using-json) – Shlomi Schwartz Feb 26 '13 at 09:02
  • If you don't have a domain class (i.e.the json its input data only), is there any way to parse the jsonObject? Obviously one can do def x = jsonOblect.xxx, but how to you iterate over collections in the bowels of the json? – John Little Aug 22 '16 at 14:53
6

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)

    }
Mike Sickler
  • 33,662
  • 21
  • 64
  • 90
  • Thanks Mike! Are there any other variables/ways of getting posted data other than params? That's what's really causing me the most pain. – maximus Jun 11 '10 at 04:21
  • You know what, I found out that I wasn't posting the json, that's why it never appeared in params. So, your solution works out just fine. Thanks again! – maximus Jun 15 '10 at 03:52