Groovy Guide — JSON: Parsing and Generating JSON
In this tutorial, you will learn about Groovy Guide. We cover key concepts, practical examples, and best practices to help you master this topic.
Groovy JSON support includes JsonSlurper for parsing JSON to Groovy objects, JsonOutput for Serialization, and JsonBuilder for constructing JSON structures with Builder syntax.
What You'll Learn
- JsonSlurper for parsing
- JsonOutput for generation
- JsonBuilder for DSL construction
- Working with JSON arrays
- Pretty printing
Why It Matters
JSON is the dominant data format for APIs and configuration. Groovy's JSON tools make parsing and generation seamless. Durga Antivirus Pro uses JSON for API integration.
Real-World Use
REST API clients, configuration files, data serialization, and web service communication.
flowchart LR
A["JSON"] --> B["JsonSlurper"]
B --> C["JsonOutput"]
C --> D["JsonBuilder"]
D --> E["Advanced"]
A:::current --> B
style A fill:#2563eb,stroke:#2563eb,color:#fff
style B fill:#dbeafe,stroke:#2563eb,color:#1e40af
style C fill:#dbeafe,stroke:#2563eb,color:#1e40af
style D fill:#dbeafe,stroke:#2563eb,color:#1e40af
style E fill:#f1f5f9,stroke:#94a3b8,color:#64748b
JsonSlurper
import groovy.json.JsonSlurper
def json = '''
{
"name": "Alice",
"age": 30,
"email": "alice@example.com",
"active": true,
"skills": ["Java", "Groovy"]
}
'''
def data = new JsonSlurper().parseText(json)
data.name // "Alice"
data.age // 30
data.skills // ["Java", "Groovy"]
Parsing from Sources
// From string
def data = new JsonSlurper().parseText(jsonString)
// From file
def data = new JsonSlurper().parse(new File("data.json"))
// From URL
def data = new JsonSlurper().parse(new URL("http://api.example.com/data"))
// From reader
def data = new JsonSlurper().parse(new FileReader("data.json"))
JsonOutput
import groovy.json.JsonOutput
def data = [name: "Alice", age: 30, skills: ["Java", "Groovy"]]
// Serialize to JSON
def json = JsonOutput.toJson(data)
// {"name":"Alice","age":30,"skills":["Java","Groovy"]}
// Pretty print
def pretty = JsonOutput.prettyPrint(json)
// Custom serialization
def custom = JsonOutput.toJson([
name: "Bob",
date: new Date(),
null: null,
nested: [a: 1, b: 2]
])
JsonBuilder
import groovy.json.JsonBuilder
def json = new JsonBuilder()
json {
name "Alice"
age 30
address {
city "Portland"
state "OR"
}
skills "Java", "Groovy", "Python"
}
println json.toPrettyString()
JsonBuilder with Arrays
import groovy.json.JsonBuilder
def json = new JsonBuilder()
json.users([
[name: "Alice", age: 30],
[name: "Bob", age: 25]
])
// Or builder syntax for array
def json2 = new JsonBuilder()
json2 {
users {
user(name: "Alice", age: 30)
user(name: "Bob", age: 25)
}
}
StreamingJsonBuilder
import groovy.json.StreamingJsonBuilder
def writer = new StringWriter()
def json = new StreamingJsonBuilder(writer)
json {
name "Alice"
age 30
skills "Groovy", "Java"
}
println writer.toString()
Custom JSON Parsing
import groovy.json.JsonSlurper
// Configure parser
def slurper = new JsonSlurper()
slurper.setType(Map)
// Handle dates
def json = '{"date": "2024-01-15"}'
def data = slurper.parseText(json)
// date is a String, not Date
// Custom conversion
def withDates = slurper.parseText(json).collectEntries { k, v ->
[k, k == "date" ? Date.parse("yyyy-MM-dd", v) : v]
}
Common Mistakes
1. Assuming type conversion
JsonSlurper returns maps/lists, not domain objects. Use libraries like Jackson for full deserialization.
2. Date handling
JSON has no date type. Dates are strings. Parse them explicitly.
3. Pretty print performance
JsonOutput.prettyPrint is for development. Use compact JSON in production.
4. Null values in maps
JsonOutput includes null values. Filter nulls with findAll before serialization.
5. Large JSON parsing
JsonSlurper loads the entire document. For streaming, use JsonSlurper with InputStream.
Practice Questions
1. What does JsonSlurper do? Parses JSON text into Groovy data structures (maps, lists, strings, numbers).
2. What is the difference between JsonOutput and JsonBuilder? JsonOutput serializes existing objects. JsonBuilder constructs JSON using closure DSL syntax.
3. How do you pretty-print JSON?
Use JsonOutput.prettyPrint(jsonString) to format JSON with indentation.
Challenge: Write a Groovy script that reads a JSON config file, modifies a value, and writes it back.
FAQ
{{< faq question="Is JsonSlurper thread-safe?" >} No. Create a new JsonSlurper instance per thread or use synchronization. {{< /faq >}}
{{< faq question="Can JsonSlurper handle arrays at root?" >}
Yes. [1, 2, 3] parses to a Groovy list. Works the same as object root.
{{< /faq >}}
{{< faq question="What is StreamingJsonBuilder?" >} A memory-efficient JSON builder that writes directly to a writer without building an in-memory representation. {{< /faq >}}
{{< faq question="How do I handle JSON with comments?" >} JSON doesn't support comments. Remove them with regex before parsing or use a relaxed parser. {{< /faq >}}
{{< faq question="Can Groovy serialize custom classes?" >} JsonOutput serializes public properties. For custom serialization, implement JsonSerializable or use annotations. {{< /faq >}}
Mini Project
Build a JSON configuration manager:
import groovy.json.JsonSlurper
import groovy.json.JsonOutput
class ConfigManager {
def data
def load(String path) {
data = new JsonSlurper().parse(new File(path))
}
def get(String path) {
path.split("\\.").inject(data) { obj, key ->
obj?."$key"
}
}
def set(String path, value) {
def parts = path.split("\\.")
def target = parts[0..-2].inject(data) { obj, key ->
obj."$key"
}
target[parts[-1]] = value
}
def save(String path) {
new File(path).text = JsonOutput.prettyPrint(JsonOutput.toJson(data))
}
}
def config = new ConfigManager()
config.load("config.json")
println config.get("database.host")
config.set("database.host", "prod.example.com")
config.save("config.json")
What's Next
Now that you understand JSON processing, explore file I/O operations.
| Topic | Description | Link |
|---|---|---|
| Groovy File I/O | File operations | {{< ref "12-file-io" >}} |
| Groovy SQL | Database access | {{< ref "13-sql" >}} |
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro