Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting JSON data on server side with Grails

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

like image 908
maximus Avatar asked Jun 11 '10 02:06

maximus


People also ask

How do I send and receive JSON data from server?

Send JSON Data from the Client SideCreate a JavaScript object using the standard or literal syntax. Use JSON. stringify() to convert the JavaScript object into a JSON string. Send the URL-encoded JSON string to the server as part of the HTTP Request.

How to access JSON data JS?

To access the JSON object in JavaScript, parse it with JSON. parse() , and access it via “.” or “[]”.

Can you embed JSON in JavaScript?

The JSON format is syntactically identical to the code for creating JavaScript objects. Because of this similarity, a JavaScript program can easily convert JSON data into native JavaScript objects.

What can I do with JSON data?

The most common use of JSON data and files is to read data from a server for a website or web application to display — and change data given the correct permissions. But, that is not the only thing it is used for. Computer applications, programs, mobile apps, and much more all use JSON files.


2 Answers

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) 
like image 55
Daniel Rinser Avatar answered Sep 23 '22 10:09

Daniel Rinser


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)      } 
like image 45
Mike Sickler Avatar answered Sep 22 '22 10:09

Mike Sickler