Mar 22, 2012

Grails ProTip: Dynamically creating JSON in Grails 2.0 with JsonBuilder




GrailsProTipJsonBuilder.html

In January I did a talk enumerating all the features in Grails 2.0 that I was excited about and one topics that made the list was the new JsonBuilder that came with the inclusion of Groovy 1.8.

The new groovy.json.JsonBuilder is the third incarnation of its ilk replacing the grails.web.JSONBuilder, which in-turn replaced the grails.util.JSonBuilder of the long-ago days of Grails 0.2 . ( Note the subtile but important change in package name and capitalization of the builder name )

So what’s different?

The previous versions built the JSON in a similar fashion to the way the MarkupBuilder builds up html. Basically each closure build is a node in the graph and you can iterate over collections to build out a collection of nodes. This is very handy.

The one thing that these older builders failed to account for was that, in JSON, collections are not sub-nodes nested under a parent node, like we would see in output form an groovy.xml.MarkupBuilder.

They are in fact a key-value pair with a string as the key and a javascript array of javascript objects as the value.

This article does a really good job describing what is going on under the hood, the issue with collections, and why the current mindset of iteration over collections to build out your JSON will simply not work.

The author gives a example of what you need to do to work collection using the JsonBuilder but he fails to show properly the most useful use case in a Grails application, which is…

Converting a graph of objects into JSON

In the code example below we have two classes the make up a simple object graph. Basically a Person has multiple Addresses.

The key to working with collections is to convert them a list of maps via the collect closure. The ‘collect’ closure is ideal here because we can iterate over the collection, whilst transforming each entity into a proper key-value pair and adding it to the list that is the result of the closure.

The nice thing is that this can be done dynamically, and right within the builder.

Running the above code will yield nice, syntactically correct, JSON when we call the toPrettyString() method on the builder like this:


About the Author

Object Partners profile.

One thought on “Grails ProTip: Dynamically creating JSON in Grails 2.0 with JsonBuilder

  1. crazy4groovy says:

    Why not use a GPath expression for addresses?

    def root = builder.people {
    person {
    name “${p.name}”
    addresses(
    p.addresses // GPath
    )
    }
    }

  2. blacar says:

    Would it be possible fo find anywhere examples with a different structure? … i see always the same people example while i need something like this:

    {“type”:”typeValue”,”collection”:[{“name1″:”value1”}, {“name2″:”value2”}]}

    Thanks in advance,

  3. Jerry Wiltse says:

    I’ve been experimenting a lot lately with these structures, and the JSONBuilder is incredibly smart and powerful. For anyone looking to “condense” json builders, line 18-32 could all be replaced by the following:

    def builder = new JsonBuilder(new Expando(‘people’: p))
    println builder.toPrettyString()

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Blog Posts
Android Development for iOS Developers
Android development has greatly improved since the early days. Maybe you tried it out when Android development was done in Eclipse, emulators were slow and buggy, and Java was the required language. Things have changed […]
Add a custom object to your Liquibase diff
Adding a custom object to your liquibase diff is a pretty simple two step process. Create an implementation of DatabaseObject Create an implementation of SnapshotGenerator In my case I wanted to add tracking of Stored […]
Keeping Secrets Out of Terraform State
There are many instances where you will want to create resources via Terraform with secrets that you just don’t want anyone to see. These could be IAM credentials, certificates, RDS DB credentials, etc. One problem […]
Validating Terraform Plans using Open Policy Agent
When developing infrastructure as code using terraform, it can be difficult to test and validate changes without executing the code against a real environment. The feedback loop between writing a line of code and understanding […]