Saturday, November 7, 2009

Grails and JSON are pretty Groovy!

Once again the incredible productivity boosts provided by Grails have become glaringly obvious.... what is it this time???? Dealing with JSON!!

In my project I needed to save domain info to files and these domains contained domains so I thought the easiest way would be XML and JSON.... having done some work in XML in Grails I decided to see how I fared in JSON.

Here's what happened:


import grails.converters.*

def report = MyDomain.get(1)
def json = ""
JSON.use("deep") {
def converter = report as JSON
converter.prettyPrint = true
json = converter.toString()
}



First off I grab a domain instance and then convert it to JSON using grails.converters.JSON. Note that grails.converters.deep is deprecated so to render your domain "deeply" you must use the configuration name "deep". I also grab the converter so I can alter some settings, specifically prettyPrint. This will render your domain in nicely formatted JSON!

So now I have a JSON string, how can I access its properties.... do I have to parse it by hand???? Fat chance...



def jsonArray = JSON.parse(json)

println jsonArray.myDomainProperty



So now we use JSON.parse() to convert our json String to an object that allows us to access our domain properties... sweet!

So there we have it, domain to json and back to an object that we could, if we wanted to, convert back to a domain...

Hope this saves people some time. Parsing and creating JSON???? Let Grails do the work...... again! :)