Geeks With Blogs
Zakaria's Blog
XML and JSON Responses
Using the render method to output XML
Grails supports a few different ways to produce XML and JSON responses. The first is the render method.
The render method can be passed a block of code to do mark-up building in XML :
 def list() {  
 def results = Book.list()  
 render(contentType: "text/xml") {  
 books {  
 for (b in results) {  
 book(title: b.title)  
 }  
 }  
 }  
 }  
The result of this code would be something like :
 <books>  
 <book title="The Stand" />  
 <book title="The Shining" />  
 </books>  
Be careful to avoid naming conflicts when using mark-up building. For example this code would produce an error
 def list() {  
 def books = Book.list() // naming conflict here  
 render(contentType: "text/xml") {  
 books {  
 for (b in results) {  
 book(title: b.title)  
 }  
 }  
 }  
 }  
This is because there is local variable books which Groovy attempts to invoke as a method.
Using the render method to output JSON
The render method can also be used to output JSON:
 def list() {  
 def results = Book.list()  
 render(contentType: "application/json") {  
 books = array {  
 for (b in results) {  
 book title: b.title  
 }  
 }  
 }  
 }  
In this case the result would be something along the lines of :
 [  
 {"title":"The Stand"},  
 {"title":"The Shining"}  
 ]  
The same dangers with naming conflicts described above for XML also apply to JSON building.
Automatic XML Marshalling
Grails also supports automatic marshalling of domain classes to XML using special converters.
To start off with, import the grails.converters package into your controller :
 import grails.converters.*  
Now you can use the following highly readable syntax to automatically convert domain classes to XML :
 render Book.list() as XML  
The resulting output would look something like the following :
 <?xml version="1.0" encoding="ISO-8859-1"?>  
 <list>  
 <book id="1">  
 <author>Stephen King</author>  
 <title>The Stand</title>  
 </book>  
 <book id="2">  
 <author>Stephen King</author>  
 <title>The Shining</title>  
 </book>  
 </list>  
For more information on XML marshalling see the section on REST
Automatic JSON Marshalling
Grails also supports automatic marshalling to JSON using the same mechanism. Simply substitute XML with JSON :
 render Book.list() as JSON  
The resulting output would look something like the following :
 [  
 {"id":1,  
 "class":"Book",  
 "author":"Stephen King",  
 "title":"The Stand"},  
 {"id":2,  
 "class":"Book",  
 "author":"Stephen King",  
 "releaseDate":new Date(1194127343161),  
 "title":"The Shining"}  
 ]  
More on JSONBuilder
The previous section on on XML and JSON responses covered simplistic examples of rendering XML and JSON the XML builder used by Grails is the standard XmlSlurper found in Groovy, the JSON builder is a custom implementation to Grails.
JSONBuilder and Grails versions
JSONBuilder behaves different depending on the version of Grails you use. For version below 1.2 grails.web.JSONBuilder class is used. This section covers the usage of the Grails 1.2 JSONBuilder
For backwards compatibility the old JSONBuilder class is used with the render method for older applications; newer/better JSONBuilder class set the following in Config.groovy :
 grails.json.legacy.builder = false  
Rendering Simple Objects
To render a simple JSON object just set properties within the context of the Closure :
 render(contentType: "application/json") {  
 hello = "world"  
 }  
The above will produce the JSON :
 {"hello":"world"}  
Rendering JSON Arrays
To render a list of objects simple assign a list :
 render(contentType: "application/json") {  
 categories = ['a', 'b', 'c']  
 }  
This will produce :
 {"categories":["a","b","c"]}  
You can also render lists of complex objects, for example :
 render(contentType: "application/json") {  
 categories = [ { a = "A" }, { b = "B" } ]  
 }  
This will produce :
 {"categories":[ {"a":"A"} , {"b":"B"}] }  
Use the special element method to return a list as the root :
 render(contentType: "application/json") {  
 element 1  
 element 2  
 element 3  
 }  
The above code produces :
 [1,2,3]  
Rendering Complex Objects
Rendering complex objects can be done with Closures. For example :
 render(contentType: "application/json") {  
 categories = ['a', 'b', 'c']  
 title = "Hello JSON"  
 information = {  
 pages = 10  
 }  
 }  
The above will produce the JSON :
 {"categories":["a","b","c"],"title":"Hello JSON","information":{"pages":10}}  
Arrays of Complex Objects
As mentioned previously you can nest complex objects within arrays using Closures :
 render(contentType: "application/json") {  
 categories = [ { a = "A" }, { b = "B" } ]  
 }  
You can use the array method to build them up dynamically :
 def results = Book.list()  
 render(contentType: "application/json") {  
 books = array {  
 for (b in results) {  
 book title: b.title  
 }  
 }  
 }  
Direct JSONBuilder API Access
If you don't have access to the render method, but still want to produce JSON you can use the API directly :
 def builder = new JSONBuilder()  
 def result = builder.build {  
 categories = ['a', 'b', 'c']  
 title = "Hello JSON"  
 information = {  
 pages = 10  
 }  
 }  
 // prints the JSON text  
 println result.toString()  
 def sw = new StringWriter()  
 result.render sw  
Uploading Files
Programmatic File Uploads
Grails supports file uploads using Spring's MultipartHttpServletRequest interface. The first step for file uploading multipart form like this :
 Upload Form: <br />  
 <g:uploadForm action="upload">  
 <input type="file" name="myFile" />  
 <input type="submit" />  
 </g:uploadForm>  
The uploadForm tag conveniently adds the enctype="multipart/form-data" attribute to the standard There are then a number of ways to handle the file upload. One is to work with the Spring MultipartFile instance
 def upload() {  
 def f = request.getFile('myFile')  
 if (f.empty) {  
 flash.message = 'file cannot be empty'  
 render(view: 'uploadForm')  
 return  
 }  
 f.transferTo(new File('/some/local/dir/myfile.txt'))  
 response.sendError(200, 'Done')  
 }  
This is convenient for doing transfers to other destinations and manipulating the file directly as you can obtain an and so on with the MultipartFile interface.
File Uploads through Data Binding
File uploads can also be performed using data binding. Consider this Image domain class :
 class Image {  
 byte[] myFile  
 static constraints = {  
 // Limit upload file size to 2MB  
 myFile maxSize: 1024 * 1024 * 2  
 }  
 }  
If you create an image using the params object in the constructor as in the example below, Grails will automatically contents as a byte to the myFile property :
 def img = new Image(params)  
It's important that you set the size or maxSize constraints, otherwise your database may be created with a small can't handle reasonably sized files. For example, both H2 and MySQL default to a blob size of 255 bytes for byte It is also possible to set the contents of the file as a string by changing the type of the myFile property on the type :
 class Image {  
 String myFile  
 }  

Posted on Sunday, July 6, 2014 2:23 PM Grails | Back to top


Comments on this post: Grails Basic-Controllers(Part 3)

No comments posted yet.
Your comment:
 (will show your gravatar)


Copyright © A.K.M. Zakaria | Powered by: GeeksWithBlogs.net