Apache Groovy is a powerful multi-faceted programming language for the JVM platform
—
Comprehensive JSON parsing, generation, and manipulation capabilities through JsonSlurper for parsing JSON data and JsonBuilder for creating JSON output with full type safety and streaming support.
High-performance JSON parser that converts JSON text into Groovy data structures (Maps, Lists, primitive types).
/**
* Main JSON parser that converts JSON text into native Groovy objects
*/
class JsonSlurper {
/**
* Parse JSON from a String
*/
Object parseText(String text);
/**
* Parse JSON from a Reader
*/
Object parse(Reader reader);
/**
* Parse JSON from a File
*/
Object parse(File file);
/**
* Parse JSON from a URL
*/
Object parse(URL url);
/**
* Parse JSON from an InputStream with specified encoding
*/
Object parse(InputStream input, String charset);
/**
* Parse JSON from a character array
*/
Object parse(char[] text);
/**
* Set the parser type for different performance characteristics
*/
void setType(JsonParserType type);
}
/**
* Enumeration of available JSON parser implementations
*/
enum JsonParserType {
CHARACTER_SOURCE, // Default parser, good balance of speed and memory
LAX, // Lenient parser, allows non-standard JSON
INDEX_OVERLAY // Fastest parser for large documents
}Usage Examples:
import groovy.json.JsonSlurper
def jsonSlurper = new JsonSlurper()
// Parse simple JSON string
def result = jsonSlurper.parseText('{"name": "John", "age": 30}')
assert result.name == "John"
assert result.age == 30
// Parse JSON array
def list = jsonSlurper.parseText('[1, 2, 3, {"nested": true}]')
assert list.size() == 4
assert list[3].nested == true
// Parse from file
def config = jsonSlurper.parse(new File('config.json'))
// Parse from URL
def apiData = jsonSlurper.parse(new URL('https://api.example.com/data'))
// Configure parser type for performance
jsonSlurper.type = JsonParserType.LAX
def relaxedJson = jsonSlurper.parseText('{name: "unquoted keys allowed"}')Fluent API for creating JSON output with support for nested structures and streaming.
/**
* Builder for creating JSON output using a fluent API
*/
class JsonBuilder {
/**
* Create empty JsonBuilder
*/
JsonBuilder();
/**
* Create JsonBuilder with initial content
*/
JsonBuilder(Object content);
/**
* Build JSON using closure-based DSL
*/
void call(Closure closure);
/**
* Build JSON with single argument
*/
void call(Object... args);
/**
* Get the built JSON as a String
*/
String toString();
/**
* Get the built content as native Groovy object
*/
Object getContent();
/**
* Write JSON to a Writer
*/
Writer writeTo(Writer writer);
}
/**
* Memory-efficient streaming JSON builder for large documents
*/
class StreamingJsonBuilder {
/**
* Create StreamingJsonBuilder with Writer output
*/
StreamingJsonBuilder(Writer writer);
/**
* Create StreamingJsonBuilder with OutputStream
*/
StreamingJsonBuilder(OutputStream output);
/**
* Create StreamingJsonBuilder with OutputStream and encoding
*/
StreamingJsonBuilder(OutputStream output, String charset);
/**
* Build JSON using closure-based DSL
*/
void call(Closure closure);
/**
* Build JSON with arguments
*/
void call(Object... args);
}Usage Examples:
import groovy.json.JsonBuilder
import groovy.json.StreamingJsonBuilder
// Simple JSON building
def builder = new JsonBuilder()
builder {
name "John Doe"
age 30
address {
street "123 Main St"
city "Anytown"
zipCode "12345"
}
hobbies(["reading", "swimming", "coding"])
}
println builder.toString()
// Output: {"name":"John Doe","age":30,"address":{"street":"123 Main St","city":"Anytown","zipCode":"12345"},"hobbies":["reading","swimming","coding"]}
// Build from existing data
def person = [name: "Jane", age: 25]
def personJson = new JsonBuilder(person)
// Complex nested structure
def complexBuilder = new JsonBuilder()
complexBuilder {
users {
user1 {
name "Alice"
roles(["admin", "user"])
settings {
theme "dark"
notifications true
}
}
user2 {
name "Bob"
roles(["user"])
}
}
metadata {
version "1.0"
timestamp new Date().time
}
}
// Streaming builder for large documents
def output = new StringWriter()
def streamingBuilder = new StreamingJsonBuilder(output)
streamingBuilder {
largeDataSet {
(1..1000).each { i ->
"item$i" {
id i
value "data-$i"
}
}
}
}Advanced JSON output formatting and configuration options.
/**
* Configuration options for JSON generation
*/
class JsonGenerator {
/**
* Create generator with default options
*/
static JsonGenerator createDefault();
/**
* Create generator with custom options
*/
static JsonGenerator create(JsonGenerator.Options options);
/**
* Convert object to JSON string
*/
String toJson(Object object);
/**
* Write object as JSON to Writer
*/
void writeJson(Object object, Writer writer);
/**
* Configuration options for JSON generation
*/
static class Options {
Options excludeNulls();
Options excludeFieldsByName(String... names);
Options excludeFieldsByType(Class... types);
Options addConverter(Class type, Closure converter);
Options dateFormat(String format);
Options disableUnicodeEscaping();
}
}Usage Examples:
import groovy.json.JsonGenerator
// Custom JSON generation with options
def generator = JsonGenerator.create {
excludeNulls()
dateFormat('yyyy-MM-dd')
excludeFieldsByName('password', 'secret')
}
def user = [
name: "John",
password: "secret123",
email: "john@example.com",
lastLogin: new Date(),
metadata: null
]
def json = generator.toJson(user)
// Output excludes 'password' and 'metadata' fields, formats date
// Custom type converters
def customGenerator = JsonGenerator.create {
addConverter(URL) { url -> url.toString() }
addConverter(File) { file -> file.absolutePath }
}Navigate and extract data from parsed JSON using GPath expressions.
Usage Examples:
import groovy.json.JsonSlurper
def jsonText = '''
{
"company": "TechCorp",
"employees": [
{"name": "Alice", "department": "Engineering", "salary": 85000},
{"name": "Bob", "department": "Marketing", "salary": 65000},
{"name": "Carol", "department": "Engineering", "salary": 90000}
],
"locations": {
"headquarters": "New York",
"branches": ["California", "Texas", "Florida"]
}
}
'''
def company = new JsonSlurper().parseText(jsonText)
// Simple property access
assert company.company == "TechCorp"
// Array access and filtering
def engineers = company.employees.findAll { it.department == "Engineering" }
assert engineers.size() == 2
// Nested property access
assert company.locations.headquarters == "New York"
assert company.locations.branches[0] == "California"
// Sum calculations
def totalSalary = company.employees.sum { it.salary }
assert totalSalary == 240000
// Find specific employee
def alice = company.employees.find { it.name == "Alice" }
assert alice.salary == 85000Handle malformed JSON and validate JSON structure.
Usage Examples:
import groovy.json.JsonSlurper
import groovy.json.JsonException
def jsonSlurper = new JsonSlurper()
try {
def result = jsonSlurper.parseText('{"invalid": json}')
} catch (JsonException e) {
println "Invalid JSON: ${e.message}"
}
// Validate JSON structure
def validateUser = { json ->
def required = ['name', 'email', 'age']
def missing = required.findAll { !json.containsKey(it) }
if (missing) {
throw new IllegalArgumentException("Missing required fields: $missing")
}
return json
}
def userData = jsonSlurper.parseText('{"name": "John", "email": "john@example.com", "age": 30}')
validateUser(userData)/**
* Exception thrown when JSON parsing fails
*/
class JsonException extends RuntimeException {
JsonException(String message);
JsonException(String message, Throwable cause);
}
/**
* Parser type enumeration for different parsing strategies
*/
enum JsonParserType {
/**
* Default character-based parser with good balance of performance and memory usage
*/
CHARACTER_SOURCE,
/**
* Lenient parser that accepts non-standard JSON formats
*/
LAX,
/**
* Fastest parser optimized for large documents using index overlays
*/
INDEX_OVERLAY
}/**
* Options for configuring JSON output generation
*/
interface JsonGenerator.Options {
/**
* Exclude null values from JSON output
*/
Options excludeNulls();
/**
* Exclude specific fields by name
*/
Options excludeFieldsByName(String... names);
/**
* Exclude fields of specific types
*/
Options excludeFieldsByType(Class... types);
/**
* Add custom type converter
*/
Options addConverter(Class type, Closure converter);
/**
* Set date formatting pattern
*/
Options dateFormat(String format);
/**
* Disable Unicode character escaping
*/
Options disableUnicodeEscaping();
}Install with Tessl CLI
npx tessl i tessl/maven-org-codehaus-groovy--groovy