JSON library for the Apache Groovy programming language providing JSON parsing, generation, and manipulation capabilities
—
DSL-based JSON building with Groovy's closure syntax, supporting both in-memory and streaming approaches for flexible JSON construction.
In-memory JSON builder using Groovy's dynamic method invocation and closure syntax for intuitive JSON construction.
/**
* In-memory JSON builder with DSL syntax support
*/
public class JsonBuilder extends GroovyObjectSupport implements Writable {
/** Default constructor */
public JsonBuilder();
/** Constructor with custom JSON generator */
public JsonBuilder(JsonGenerator generator);
/** Constructor with initial content */
public JsonBuilder(Object content);
public JsonBuilder(Object content, JsonGenerator generator);
/** Get the internal content structure */
public Object getContent();
/** Create root JSON object from Map */
public Object call(Map m);
/** Create root JSON array from List */
public Object call(List l);
/** Create root JSON array from varargs */
public Object call(Object... args);
/** Create array applying closure to collection */
public Object call(Iterable coll, Closure c);
public Object call(Collection coll, Closure c);
/** Create root JSON object from closure */
public Object call(Closure c);
/** Dynamic method calls for JSON structure building */
public Object invokeMethod(String name, Object args);
/** Serialize to JSON string */
public String toString();
/** Pretty-print JSON with formatting */
public String toPrettyString();
/** Write JSON to Writer (Writable interface) */
public Writer writeTo(Writer out) throws IOException;
}Usage Examples:
import groovy.json.JsonBuilder;
// Basic object construction
JsonBuilder json = new JsonBuilder();
json.user {
name "Alice"
age 30
email "alice@example.com"
}
String result = json.toString();
// {"user":{"name":"Alice","age":30,"email":"alice@example.com"}}
// Nested structures
JsonBuilder json = new JsonBuilder();
json.company {
name "ACME Corp"
employees {
engineering([
[name: "Bob", role: "Senior Developer"],
[name: "Carol", role: "Tech Lead"]
])
marketing([
[name: "David", role: "Manager"]
])
}
headquarters {
street "123 Main St"
city "San Francisco"
state "CA"
zipCode "94102"
}
}
// Array construction
JsonBuilder json = new JsonBuilder();
json([
[id: 1, title: "First Post", published: true],
[id: 2, title: "Draft Post", published: false]
]);
// Using collections with closures
List<String> names = ["Alice", "Bob", "Charlie"];
JsonBuilder json = new JsonBuilder();
json.users(names) { name ->
[
username: name.toLowerCase(),
displayName: name,
active: true
]
}
// From existing data
Map<String, Object> userData = [
id: 123,
name: "John Doe",
preferences: [theme: "dark", notifications: true]
];
JsonBuilder json = new JsonBuilder(userData);Memory-efficient JSON builder that writes directly to a Writer, ideal for large JSON documents.
/**
* Memory-efficient streaming JSON builder
*/
public class StreamingJsonBuilder extends GroovyObjectSupport {
/** Constructor with Writer */
public StreamingJsonBuilder(Writer writer);
/** Constructor with Writer and custom generator */
public StreamingJsonBuilder(Writer writer, JsonGenerator generator);
/** Constructor with Writer and initial content */
public StreamingJsonBuilder(Writer writer, Object content) throws IOException;
public StreamingJsonBuilder(Writer writer, Object content, JsonGenerator generator) throws IOException;
/** Write Map as JSON object */
public Object call(Map m) throws IOException;
/** Write empty object with name */
public void call(String name) throws IOException;
/** Write List as JSON array */
public Object call(List l) throws IOException;
/** Write varargs as JSON array */
public Object call(Object... args) throws IOException;
/** Write collection with closure transformation */
public Object call(Iterable coll, Closure c) throws IOException;
public Object call(Collection coll, Closure c) throws IOException;
/** Write closure as JSON object */
public Object call(Closure c) throws IOException;
/** Write named object from closure */
public void call(String name, Closure c) throws IOException;
/** Write named array with closure transformation */
public void call(String name, Iterable coll, Closure c) throws IOException;
public void call(String name, Collection coll, Closure c) throws IOException;
/** Write named object merging map and closure */
public void call(String name, Map map, Closure callable) throws IOException;
/** Dynamic method calls for JSON structure */
public Object invokeMethod(String name, Object args);
}Usage Examples:
import groovy.json.StreamingJsonBuilder;
import java.io.StringWriter;
import java.io.FileWriter;
// Basic streaming to StringWriter
StringWriter writer = new StringWriter();
StreamingJsonBuilder json = new StreamingJsonBuilder(writer);
json.user {
id 123
name "Alice"
roles(["admin", "user"])
}
String result = writer.toString();
// Streaming large datasets to file
FileWriter fileWriter = new FileWriter("large-data.json");
StreamingJsonBuilder json = new StreamingJsonBuilder(fileWriter);
json.response {
status "success"
data {
// Stream large collection without loading all into memory
users(userRepository.streamAll()) { user ->
[
id: user.getId(),
name: user.getName(),
email: user.getEmail()
]
}
}
metadata {
generatedAt new Date()
count userRepository.count()
}
}
fileWriter.close();
// Streaming with named elements
StringWriter writer = new StringWriter();
StreamingJsonBuilder json = new StreamingJsonBuilder(writer);
json {
call("timestamp", System.currentTimeMillis())
call("data", dataList) { item ->
[processed: processItem(item), index: dataList.indexOf(item)]
}
}Internal delegate class for streaming JSON operations, exposed for advanced usage patterns.
/**
* Delegate for streaming JSON building operations
*/
public static class StreamingJsonDelegate extends GroovyObjectSupport {
/** Constructor */
public StreamingJsonDelegate(Writer w, boolean first);
public StreamingJsonDelegate(Writer w, boolean first, JsonGenerator generator);
/** Get underlying writer */
public Writer getWriter();
/** Dynamic method handling for JSON structure */
public Object invokeMethod(String name, Object args);
/** Write named array */
public void call(String name, List<Object> list) throws IOException;
public void call(String name, Object... array) throws IOException;
/** Write named array with closure transformation */
public void call(String name, Iterable coll, Closure c) throws IOException;
public void call(String name, Collection coll, Closure c) throws IOException;
/** Write named value */
public void call(String name, Object value) throws IOException;
/** Write named object with closure */
public void call(String name, Object value, Closure callable) throws IOException;
public void call(String name, Closure value) throws IOException;
/** Write unescaped JSON */
public void call(String name, JsonOutput.JsonUnescaped json) throws IOException;
/** Write Writable as value */
public void call(String name, Writable json) throws IOException;
}Utility delegate for closures representing JSON objects, enabling Groovy's DSL syntax. This class is used internally by JsonBuilder to provide the dynamic method invocation capabilities.
/**
* Delegate for closures representing JSON objects
*/
public class JsonDelegate extends GroovyObjectSupport {
/** Constructor */
public JsonDelegate();
/** Intercept method calls for JSON key/value pairs */
public Object invokeMethod(String name, Object args);
/** Get content map */
public Map<String, Object> getContent();
/** Create delegate from closure */
public static Map<String, Object> cloneDelegateAndGetContent(Closure<?> c);
/** Create delegate with curried closure */
public static Map<String, Object> curryDelegateAndGetContent(Closure<?> c, Object o);
/** Create delegate with generator and curried closure */
public static Map<String, Object> curryDelegateAndGetContent(Closure<?> c, Object o, JsonGenerator generator);
}Usage Examples:
import groovy.json.JsonDelegate;
import groovy.json.JsonGenerator;
// Direct usage (advanced)
JsonDelegate delegate = new JsonDelegate();
Closure<?> jsonClosure = {
name "John"
age 30
address {
street "123 Main St"
city "New York"
}
}
Map<String, Object> content = JsonDelegate.cloneDelegateAndGetContent(jsonClosure);
// Results in Map structure representing the JSON object
// Used internally by JsonBuilder for DSL support
// This enables the natural Groovy syntax:
// json.user { name "Alice"; age 25 }import groovy.json.JsonGenerator;
// Create custom generator with options
JsonGenerator generator = new JsonGenerator.Options()
.excludeNulls()
.dateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ")
.disableUnicodeEscaping()
.build();
JsonBuilder json = new JsonBuilder(generator);
json.event {
timestamp new Date()
description "Test event"
metadata null // Will be excluded
}// Use streaming builder for large datasets
FileWriter writer = new FileWriter("output.json");
StreamingJsonBuilder stream = new StreamingJsonBuilder(writer);
stream.largeDataset {
// Process data in chunks to avoid memory issues
for (int i = 0; i < 1000000; i += 1000) {
List<Object> chunk = dataService.getChunk(i, 1000);
call("batch_" + (i/1000), chunk) { item ->
[id: item.id, processed: processItem(item)]
}
}
}
writer.close();JsonBuilder json = new JsonBuilder();
json {
apiVersion "v1"
kind "ConfigMap"
metadata {
name "app-config"
namespace "production"
labels {
app "myapp"
environment "prod"
}
}
data {
"database.url" "jdbc:postgresql://db:5432/myapp"
"cache.ttl" "3600"
"features" {
enabled(["feature-a", "feature-b"])
disabled(["feature-c"])
}
}
}JSON building operations can throw IOException for streaming operations or JsonException for malformed data:
try {
FileWriter writer = new FileWriter("output.json");
StreamingJsonBuilder json = new StreamingJsonBuilder(writer);
json.data {
value "some data"
}
writer.close();
} catch (IOException e) {
System.err.println("I/O error during JSON writing: " + e.getMessage());
}Install with Tessl CLI
npx tessl i tessl/maven-org-apache-groovy--groovy-json