Dark theme | Light theme

April 27, 2011

Groovy Goodness: Build JSON with JsonBuilder and Pretty Print JSON Text

Groovy 1.8 adds JSON support. We can build a JSON data structure with the JsonBuilder class. This class functions just like other builder classes. We define a hiearchy with values and this is converted to JSON output when we view the String value. We notice the syntax is the same as for a MarkupBuilder.

import groovy.json.*

def json = new JsonBuilder()

json.message {
    header {
        from('mrhaki')  // parenthesis are optional
        to 'Groovy Users', 'Java Users'
    body "Check out Groovy's gr8 JSON support."

assert json.toString() == '{"message":{"header":{"from":"mrhaki","to":["Groovy Users","Java Users"]},"body":"Check out Groovy\'s gr8 JSON support."}}'

// We can even pretty print the JSON output
def prettyJson = JsonOutput.prettyPrint(json.toString())
assert prettyJson == '''{
    "message": {
        "header": {
            "from": "mrhaki",
            "to": [
                "Groovy Users",
                "Java Users"
        "body": "Check out Groovy's gr8 JSON support."