Skip to content
JsonBuilder and MarkupBuilder
step 1/5

Reading — step 1 of 5

Learn

~1 min readClosures and Builders

Groovy ships with builders for JSON, XML, and HTML — using closures + delegation.

JsonBuilder — JSON via DSL:

import groovy.json.JsonBuilder

def builder = new JsonBuilder()
builder.user {
    name "Ada"
    age 36
    skills(["Math", "Engines"])
    address {
        city "London"
        country "UK"
    }
}

println builder.toString()
// {"user":{"name":"Ada","age":36,"skills":["Math","Engines"],...}}

Method calls become JSON object keys. The argument is the value (or a closure becomes a nested object).

groovy.json.JsonOutput.toJson(...) — for plain Maps/Lists:

import groovy.json.JsonOutput
import groovy.json.JsonSlurper

def data = [name: "Ada", scores: [80, 92, 75]]
def jsonStr = JsonOutput.toJson(data)
def pretty = JsonOutput.prettyPrint(jsonStr)

def parsed = new JsonSlurper().parseText(jsonStr)
println parsed.scores[0]      // 80

MarkupBuilder — XML or HTML:

import groovy.xml.MarkupBuilder

def writer = new StringWriter()
def html = new MarkupBuilder(writer)
html.html {
    head { title "Hello" }
    body {
        h1 "Welcome"
        p("This is ", b("important"))
    }
}
println writer.toString()

These builders are why Groovy stuck around — concise document construction without fighting verbose libraries.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…