Groovy JsonBuilder
last modified October 15, 2026
While JsonSlurper reads JSON, its counterpart
JsonBuilder writes it. The builder turns a declarative closure into
a serialized JSON document, mirroring the tree structure in code. For lower
level control there is JsonOutput, and for streaming large
documents there is StreamingJsonBuilder. This tutorial shows how to
create JSON in Groovy with practical examples.
Building JSON with JsonBuilder
Instantiate JsonBuilder, then declare the structure with a
closure. Method calls become object keys and their arguments become values.
import groovy.json.JsonBuilder
def builder = new JsonBuilder()
builder {
name "Alice"
age 30
city "Wonderland"
}
println builder.toString()
The closure defines an object with three keys. Calling toString()
returns compact JSON such as
{"name":"Alice","age":30,"city":"Wonderland"}. Numbers, booleans,
and strings are all produced with their proper JSON types.
$ groovy SimpleJsonBuilder.groovy
{"name":"Alice","age":30,"city":"Wonderland"}
Building Nested Structures
Nesting a closure inside a closure produces a nested JSON object. This maps naturally onto domain models with sub-objects.
import groovy.json.JsonBuilder
def builder = new JsonBuilder()
builder {
name "Alice"
address {
city "Wonderland"
zip "12345"
}
}
println builder.toString()
The address key holds another object with city and
zip. The generated JSON nests them exactly as declared, which keeps
the mapping between code and output obvious.
$ groovy NestedJsonBuilder.groovy
{"name":"Alice","address":{"city":"Wonderland","zip":"12345"}}
Building Arrays
Passing a list as the argument to a key produces a JSON array of the list's elements.
import groovy.json.JsonBuilder
def builder = new JsonBuilder()
builder {
name "Shopping List"
items(["milk", "bread", "eggs"])
}
println builder.toString()
The items key receives a Groovy list, so the result contains a JSON
array. Lists of maps or nested lists are handled the same way, letting you build
arbitrarily deep structures.
$ groovy JsonArray.groovy
{"name":"Shopping List","items":["milk","bread","eggs"]}
Building an Array of Objects
To emit a top-level array of objects, pass a list of maps to
JsonBuilder or call it with a list closure.
import groovy.json.JsonBuilder
def people = [
[name: "Alice", age: 30],
[name: "Bob", age: 25]
]
def builder = new JsonBuilder(people)
println builder.toString()
Passing the list of maps to JsonBuilder serializes it directly as a
top-level array. To build the list from other data first, use
collect and pass the result in the same way.
$ groovy JsonArrayOfObjects.groovy
[{"name":"Alice","age":30},{"name":"Bob","age":25}]
Pretty Printing with JsonOutput
The JsonOutput class offers a prettyPrint method that
formats a JSON string with indentation. Pair it with toJson, which
produces the compact string from a map or list.
import groovy.json.JsonBuilder
import groovy.json.JsonOutput
def builder = new JsonBuilder([
name: "Alice",
skills: ["Groovy", "Java"]
])
println JsonOutput.prettyPrint(builder.toString())
The output is spread across multiple lines with clear indentation. Pretty printing is valuable when the JSON is meant for humans, such as debug logs or line-diffed fixtures.
$ groovy PrettyPrint.groovy
{
"name": "Alice",
"skills": [
"Groovy",
"Java"
]
}
Converting Maps and Lists with JsonOutput
You do not always need a builder. JsonOutput.toJson serializes any
map, list, or supported value in one call.
import groovy.json.JsonOutput
def data = [
id: 1,
tags: ["groovy", "json"],
active: true
]
println JsonOutput.toJson(data)
println JsonOutput.prettyPrint(JsonOutput.toJson(data))
The map is serialized with toJson, and the same string is then
reformatted with prettyPrint. Because toJson accepts
plain collections, it is the quickest path when you already have the data as
maps and lists.
$ groovy JsonOutputToJson.groovy
{"id":1,"tags":["groovy","json"],"active":true}
{
"id": 1,
"tags": [
"groovy",
"json"
],
"active": true
}
Serializing Objects
JsonOutput can also serialize a Groovy object by reading its
properties. Combined with a transform closure, you control exactly which fields
appear.
import groovy.json.JsonOutput
class User {
String name
String email
String password
}
def user = new User(name: "Alice", email: "alice@example.com",
password: "secret")
def json = JsonOutput.toJson([
name: user.name,
email: user.email
])
println json
Rather than exposing every field, the map selects only name and
email, keeping the password out of the output. Projecting objects
into maps before serialization is a simple way to enforce an API contract.
$ groovy JsonObject.groovy
{"name":"Alice","email":"alice@example.com"}
Streaming Large Documents
StreamingJsonBuilder writes JSON directly to a writer without
holding the whole document in memory. It uses the same closure syntax as
JsonBuilder.
import groovy.json.StreamingJsonBuilder
def writer = new StringWriter()
def json = new StreamingJsonBuilder(writer)
json {
people((1..3).collect { n ->
[name: "User $n", id: n]
})
}
println writer.toString()
The builder writes its output straight to the writer, so no intermediate JSON
tree is built in memory. The list passed to people is still created
in full here. For very large data, write to a file writer and feed the builder
from a streaming source, so records are never all held at once.
$ groovy StreamingJson.groovy
{"people":[{"name":"User 1","id":1},{"name":"User 2","id":2},{"name":"User 3","id":3}]}
Best Practices for Building JSON
- Choose the Right Tool: Use
JsonBuilderfor structure,JsonOutputfor one-liners, andStreamingJsonBuilderfor large payloads. - Escape Automatically: Let the builder handle quotes and special characters instead of concatenating strings yourself.
- Project Sensitive Data: Serialize explicit maps rather than whole objects to avoid leaking private fields.
- Validate Round Trips: Parse the produced JSON with
JsonSlurperin tests to confirm its shape. - Keep Keys Stable: Consistent key names make downstream consumers simpler and more predictable.
Source
In this tutorial, we created JSON with JsonBuilder, built nested
objects and arrays, pretty printed output with JsonOutput,
serialized maps and objects, and streamed large documents. Together with
JsonSlurper, these classes give Groovy a complete JSON toolkit.
Author
List all Groovy tutorials.