Apache Groovy is a powerful, optionally typed and dynamic language, with static-typing and static compilation capabilities, for the Java platform aimed at improving developer productivity thanks to a concise, familiar and easy to learn syntax.
—
Complete JSON parsing and generation with builder patterns, streaming support, and flexible configuration options for handling various JSON structures.
Parse JSON text into Groovy data structures with flexible type handling.
/**
* Parser for JSON text into Groovy data structures
*/
class JsonSlurper {
/** Create JsonSlurper with default configuration */
JsonSlurper()
/** Parse JSON from string */
Object parseText(String text)
/** Parse JSON from Reader */
Object parse(Reader reader)
/** Parse JSON from File */
Object parse(File file)
/** Parse JSON from InputStream */
Object parse(InputStream input)
/** Parse JSON from URL */
Object parse(URL url)
/** Parse JSON from character array */
Object parse(char[] text)
/** Set the type of JSON parser to use */
JsonSlurper setType(JsonParserType type)
}
/**
* Enumeration of JSON parser types
*/
enum JsonParserType {
CHARACTER_SOURCE, // Default parser
LAX, // Lenient parser allowing comments and unquoted keys
INDEX_OVERLAY // Fast parser for large JSON
}Usage Examples:
import groovy.json.JsonSlurper
// Basic JSON parsing
def jsonSlurper = new JsonSlurper()
def json = '''
{
"name": "John Doe",
"age": 30,
"active": true,
"skills": ["Java", "Groovy", "JSON"],
"address": {
"street": "123 Main St",
"city": "Anytown"
}
}
'''
def result = jsonSlurper.parseText(json)
println result.name // "John Doe"
println result.age // 30
println result.skills[0] // "Java"
println result.address.city // "Anytown"
// Parse from file
def jsonFile = new File("data.json")
result = jsonSlurper.parse(jsonFile)
// Parse from URL
result = jsonSlurper.parse(new URL("https://api.example.com/data"))
// Using different parser types
def laxSlurper = new JsonSlurper().setType(JsonParserType.LAX)
def laxJson = '''
{
// Comments are allowed in LAX mode
name: "unquoted keys allowed",
'mixed': "quote styles"
}
'''
result = laxSlurper.parseText(laxJson)Create JSON structures using a fluent builder API.
/**
* Builder for creating JSON structures
*/
class JsonBuilder {
/** Create empty JsonBuilder */
JsonBuilder()
/** Create JsonBuilder with initial value */
JsonBuilder(Object content)
/** Build JSON using closure */
Object call(Closure closure)
/** Build JSON with named arguments */
Object call(Map namedArgs, Closure closure)
/** Convert to JSON string */
String toString()
/** Convert to pretty-printed JSON string */
String toPrettyString()
/** Get the content as object */
Object getContent()
}Usage Examples:
import groovy.json.JsonBuilder
// Basic JSON building
def builder = new JsonBuilder()
builder {
name "John Doe"
age 30
active true
skills(["Java", "Groovy", "JSON"])
address {
street "123 Main St"
city "Anytown"
zipCode 12345
}
}
println builder.toString()
// Output: {"name":"John Doe","age":30,"active":true,"skills":["Java","Groovy","JSON"],"address":{"street":"123 Main St","city":"Anytown","zipCode":12345}}
println builder.toPrettyString()
// Output: formatted JSON with indentation
// Building arrays
def arrayBuilder = new JsonBuilder()
arrayBuilder([
[name: "Alice", age: 25],
[name: "Bob", age: 30],
[name: "Charlie", age: 35]
])
// Conditional building
def userBuilder = new JsonBuilder()
userBuilder {
name "User"
if (includeAge) {
age 25
}
if (includeSkills) {
skills(["Java", "Groovy"])
}
}Build JSON with streaming for large datasets.
/**
* Streaming JSON builder for large datasets
*/
class StreamingJsonBuilder {
/** Create streaming builder writing to Writer */
StreamingJsonBuilder(Writer writer)
/** Create streaming builder writing to OutputStream */
StreamingJsonBuilder(OutputStream output)
/** Build JSON using closure */
Object call(Closure closure)
/** Build JSON with named arguments */
Object call(Map namedArgs, Closure closure)
}Usage Examples:
import groovy.json.StreamingJsonBuilder
// Stream to file
def file = new File("large-data.json")
file.withWriter { writer ->
def builder = new StreamingJsonBuilder(writer)
builder {
users(users.collect { user ->
[
id: user.id,
name: user.name,
email: user.email
]
})
metadata {
total users.size()
generated new Date()
}
}
}
// Stream to HTTP response
response.contentType = "application/json"
response.withWriter { writer ->
def builder = new StreamingJsonBuilder(writer)
builder {
results data
pagination {
page currentPage
totalPages totalPageCount
hasNext currentPage < totalPageCount
}
}
}Utility methods for converting objects to JSON strings.
/**
* Utility for converting objects to JSON
*/
class JsonOutput {
/** Convert object to JSON string */
static String toJson(Object object)
/** Convert object to JSON with custom generator */
static String toJson(Object object, JsonGenerator generator)
/** Format JSON string with pretty printing */
static String prettyPrint(String jsonPayload)
/** Check if character needs JSON escaping */
static boolean isValidJsonElement(char c)
/** Escape character for JSON */
static String escapeJsonChar(char c)
}Usage Examples:
import groovy.json.JsonOutput
// Convert objects to JSON
def data = [
name: "Example",
values: [1, 2, 3, 4, 5],
enabled: true,
config: [timeout: 30, retries: 3]
]
def json = JsonOutput.toJson(data)
println json
// Output: {"name":"Example","values":[1,2,3,4,5],"enabled":true,"config":{"timeout":30,"retries":3}}
// Pretty printing
def prettyJson = JsonOutput.prettyPrint(json)
println prettyJson
// Output: formatted with indentation and line breaks
// Converting various types
println JsonOutput.toJson(new Date()) // ISO date string
println JsonOutput.toJson([1, 2, 3]) // JSON array
println JsonOutput.toJson("Hello\nWorld") // Escaped stringInterface for custom JSON generation strategies.
/**
* Interface for JSON generation strategies
*/
interface JsonGenerator {
/** Check if generator handles the given type */
boolean handles(Class<?> type)
/** Generate JSON for the given object */
Object generate(Object object, String key)
}
/**
* Default implementation of JsonGenerator
*/
class DefaultJsonGenerator implements JsonGenerator {
/** Configure options for JSON generation */
DefaultJsonGenerator(Map<String, Object> options)
/** Add converter for specific type */
DefaultJsonGenerator addConverter(Class<?> type, Closure converter)
/** Exclude fields by name */
DefaultJsonGenerator excludeFields(String... fields)
/** Exclude fields by class and field name */
DefaultJsonGenerator excludeFields(Class clazz, String... fields)
}Usage Examples:
import groovy.json.JsonGenerator
import groovy.json.DefaultJsonGenerator
import groovy.json.JsonOutput
// Custom JSON generator
def generator = new DefaultJsonGenerator([
dateFormat: "yyyy-MM-dd",
prettyPrint: true
])
// Add custom converter for specific type
generator.addConverter(java.awt.Point) { point, key ->
[x: point.x, y: point.y]
}
// Exclude sensitive fields
generator.excludeFields("password", "secret")
generator.excludeFields(User, "internalId", "createdAt")
def user = new User(name: "John", password: "secret123", email: "john@example.com")
def json = JsonOutput.toJson(user, generator)
// password field will be excluded from output/**
* Exception thrown during JSON parsing or generation
*/
class JsonException extends RuntimeException {
JsonException(String message)
JsonException(String message, Throwable cause)
}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 "JSON parsing failed: ${e.message}"
}Install with Tessl CLI
npx tessl i tessl/maven-org-apache-groovy--groovy