Working with JSON
Prerequisites: Maps, Lists
JSON support is built in (groovy.json) — no extra library needed.
Parsing
import groovy.json.JsonSlurper
def text = '''
{
"name": "tools-api",
"version": "2.1.0",
"private": false,
"maintainers": [
{"name": "Ada", "email": "ada@example.com"},
{"name": "Linus", "email": null}
],
"limits": {"rps": 50, "burst": 120}
}
'''
def json = new JsonSlurper().parseText(text)
println json.name
println json.maintainers*.name
println json.maintainers.find { !it.email }.name
println json.limits.rps * 2
println json.private.getClass().simpleName
tools-api
[Ada, Linus]
Linus
100
Boolean
JsonSlurper turns JSON objects into maps and arrays into lists, so you
navigate with the same syntax as any Groovy data. It also has
parse(File) and parse(URL).
Generating
import groovy.json.JsonOutput
def data = [
id: 7,
tags: ['groovy', 'json'],
owner: [name: 'Ada', active: true],
score: 9.5,
note: null,
]
println JsonOutput.toJson(data)
println JsonOutput.prettyPrint(JsonOutput.toJson(data))
{"id":7,"tags":["groovy","json"],"owner":{"name":"Ada","active":true},"score":9.5,"note":null}
{
"id": 7,
"tags": [
"groovy",
"json"
],
"owner": {
"name": "Ada",
"active": true
},
"score": 9.5,
"note": null
}
Paste JSON into the JSON Formatter or JSON Validator when you need to inspect it.
JsonBuilder
import groovy.json.JsonBuilder
def users = [[name: 'Ada', roles: ['admin']], [name: 'Linus', roles: []]]
def builder = new JsonBuilder()
builder {
count users.size()
items(users.collect { u ->
[name: u.name, admin: 'admin' in u.roles]
})
meta {
generator 'groovy'
}
}
println builder.toString()
{"count":2,"items":[{"name":"Ada","admin":true},{"name":"Linus","admin":false}],"meta":{"generator":"groovy"}}
JsonBuilder uses closures and method calls to describe the structure —
you'll see this builder pattern again in the next lessons.
Objects to JSON and back
import groovy.json.*
class Task { String title; boolean done; List<String> tags }
def task = new Task(title: 'Write docs', done: false, tags: ['docs'])
def jsonText = JsonOutput.toJson(task)
println jsonText
def copy = new JsonSlurper().parseText(jsonText) as Task
println "${copy.title} / ${copy.tags}"
def gen = new JsonGenerator.Options()
.excludeNulls()
.excludeFieldsByName('done')
.build()
println gen.toJson(new Task(title: 'Ship'))
{"title":"Write docs","done":false,"tags":["docs"]}
Write docs / [docs]
{"title":"Ship"}
JsonGenerator.Options customizes output — skip nulls, exclude
fields, format dates, or add converters for your own types. For large
applications, Jackson (usually via your framework) is the common
choice, and works from Groovy exactly as from Java.