JSON with JsonSlurper and JsonOutput

JSON support ships in the Groovy jar as groovy-json: JsonSlurper reads a document into maps and lists, and JsonOutput writes one back. No dependency is needed.

Parse a document

read.groovy

import groovy.json.JsonSlurper def json = '''{ "name": "Ada", "skills": ["Groovy", "Java"], "address": {"city": "London"} }''' def data = new JsonSlurper().parseText(json) println data.name println data.skills[1] println data.address.city println data.skills.size() println data.keySet().sort()

groovy read.groovy

Ada
Java
London
2
[address, name, skills]

A JSON object becomes a LazyMap, which is a Map with property access, and an array becomes an ArrayList. The last line sorts the keys, because the order of a printed map should not depend on the writer of the document.

Write JSON

write.groovy

import groovy.json.JsonOutput def person = [ name: 'Ada', skills: ['Groovy', 'Java'], active: true, address: [city: 'London'], ] println JsonOutput.toJson(person) println JsonOutput.prettyPrint(JsonOutput.toJson(person))

groovy write.groovy

{"name":"Ada","skills":["Groovy","Java"],"active":true,"address":{"city":"London"}}
{
    "name": "Ada",
    "skills": [
        "Groovy",
        "Java"
    ],
    "active": true,
    "address": {
        "city": "London"
    }
}

toJson writes the compact form an API sends, and prettyPrint indents it for a human. A map keeps its insertion order, so the output is stable; a set or a map built from a set is not, and the course sorts before it prints.

A document in a file

filejson.groovy

import groovy.json.JsonSlurper def file = new File('person.json') file.text = '{"name": "Ada", "skills": ["Groovy"]}' def person = new JsonSlurper().parse(file) println person.name println person.skills

groovy filejson.groovy

Ada
[Groovy]

parse(File) reads the file, and parse(Reader) reads a stream. An invalid document throws JsonException with the position of the problem, which is the message to show in a log rather than the contents of the file.

Related

Автор статьи: Arthur Isaev