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.

Related Blog Posts
Natively Compiled Java on Google App Engine
Google App Engine is a platform-as-a-service product that is marketed as a way to get your applications into the cloud without necessarily knowing all of the infrastructure bits and pieces to do so. Google App […]
Building Better Data Visualization Experiences: Part 2 of 2
If you don't have a Ph.D. in data science, the raw data might be difficult to comprehend. This is where data visualization comes in.
Unleashing Feature Flags onto Kafka Consumers
Feature flags are a tool to strategically enable or disable functionality at runtime. They are often used to drive different user experiences but can also be useful in real-time data systems. In this post, we’ll […]
A security model for developers
Software security is more important than ever, but developing secure applications is more confusing than ever. TLS, mTLS, RBAC, SAML, OAUTH, OWASP, GDPR, SASL, RSA, JWT, cookie, attack vector, DDoS, firewall, VPN, security groups, exploit, […]