CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-org-apache-groovy--groovy-json

JSON library for the Apache Groovy programming language providing JSON parsing, generation, and manipulation capabilities

Pending
Overview
Eval results
Files

json-output.mddocs/

JSON Output & Serialization

Comprehensive JSON serialization utilities with customizable generation, type conversion, and formatting options.

Capabilities

JsonOutput

Static utility class providing convenient methods for converting Java objects to JSON strings.

/**
 * Static utility methods for JSON serialization
 */
public class JsonOutput {
    // Character constants for JSON structure
    public static final char OPEN_BRACKET = '[';
    public static final char CLOSE_BRACKET = ']';
    public static final char OPEN_BRACE = '{';
    public static final char CLOSE_BRACE = '}';
    public static final char COLON = ':';
    public static final char COMMA = ',';
    public static final char SPACE = ' ';
    public static final char NEW_LINE = '\n';
    public static final char QUOTE = '"';
    
    /** Convert primitive types to JSON */
    public static String toJson(Boolean bool);
    public static String toJson(Number n);
    public static String toJson(Character c);
    
    /** Convert String to JSON with proper escaping */
    public static String toJson(String s);
    
    /** Convert temporal types to ISO-8601 format */
    public static String toJson(Date date);
    public static String toJson(Calendar cal);
    
    /** Convert other Java types to JSON */
    public static String toJson(UUID uuid);
    public static String toJson(URL url);
    
    /** Convert Groovy-specific types to JSON */
    public static String toJson(Closure closure);
    public static String toJson(Expando expando);
    
    /** Convert collections and objects to JSON */
    public static String toJson(Map m);
    public static String toJson(Object object);
    
    /** Pretty-print JSON strings */
    public static String prettyPrint(String jsonPayload);
    public static String prettyPrint(String jsonPayload, boolean disableUnicodeEscaping);
    
    /** Create unescaped JSON text */
    public static JsonUnescaped unescaped(CharSequence text);
}

Usage Examples:

import groovy.json.JsonOutput;
import java.util.*;

// Basic type conversion
String boolJson = JsonOutput.toJson(true);           // "true"
String numJson = JsonOutput.toJson(42);              // "42"
String strJson = JsonOutput.toJson("Hello \"World\""); // "\"Hello \\\"World\\\"\""

// Date formatting (ISO-8601)
Date now = new Date();
String dateJson = JsonOutput.toJson(now);            // "2023-12-01T10:30:45+0000"

// Map/Object conversion
Map<String, Object> data = new HashMap<>();
data.put("name", "Alice");
data.put("age", 30);
data.put("active", true);
String mapJson = JsonOutput.toJson(data);
// {"name":"Alice","age":30,"active":true}

// Pretty printing
String compact = '{"name":"Alice","details":{"age":30,"city":"NYC"}}';
String pretty = JsonOutput.prettyPrint(compact);
/*
{
    "name": "Alice",
    "details": {
        "age": 30,
        "city": "NYC"
    }
}
*/

// Unescaped content (for pre-formatted JSON)
String rawJson = '{"already":"formatted"}';
JsonOutput.JsonUnescaped unescaped = JsonOutput.unescaped(rawJson);
String combined = JsonOutput.toJson(Map.of("data", unescaped));
// {"data":{"already":"formatted"}}

JsonUnescaped

Wrapper class for JSON content that should not be escaped during serialization.

/**
 * Represents unescaped JSON text that should be inserted verbatim
 */
public static class JsonUnescaped {
    /** Constructor with text content */
    public JsonUnescaped(CharSequence text);
    
    /** Get the unescaped text */
    public CharSequence getText();
    
    /** String representation */
    public String toString();
}

JsonGenerator Interface

Interface for customizable JSON generation with advanced options and type conversion.

/**
 * Interface for customizable JSON generation
 */
public interface JsonGenerator {
    /** Convert object to JSON string */
    public String toJson(Object object);
    
    /** Check if field name should be excluded */
    public boolean isExcludingFieldsNamed(String name);
    
    /** Check if value should be excluded */
    public boolean isExcludingValues(Object value);
}

JsonGenerator.Options

Builder class for configuring JsonGenerator instances with comprehensive customization options.

/**
 * Builder for JsonGenerator configuration
 */
public static class Options {
    /** Constructor */
    public Options();
    
    /** Exclude null values from JSON output */
    public Options excludeNulls();
    
    /** Disable Unicode character escaping */
    public Options disableUnicodeEscaping();
    
    /** Set custom date format pattern */
    public Options dateFormat(String format);
    public Options dateFormat(String format, Locale locale);
    
    /** Set timezone for date formatting */
    public Options timezone(String timezone);
    
    /** Add custom type converter */
    public Options addConverter(Converter converter);
    public <T> Options addConverter(Class<T> type, Closure<?> closure);
    public <T> Options addConverter(Closure<Boolean> predicate, Closure<?> converter);
    
    /** Exclude fields by name */
    public Options excludeFieldsByName(CharSequence... fieldNames);
    public Options excludeFieldsByName(Iterable<? extends CharSequence> fieldNames);
    
    /** Exclude fields by type */
    public Options excludeFieldsByType(Class<?>... types);
    public Options excludeFieldsByType(Iterable<Class<?>> types);
    
    /** Exclude specific values from output */
    public Options excludeFieldsByValue(Object... values);
    public Options excludeFieldsByValue(Iterable<?> values);
    
    /** Build configured JsonGenerator */
    public JsonGenerator build();
}

Usage Examples:

import groovy.json.JsonGenerator;
import java.time.LocalDateTime;

// Custom generator with exclusions and formatting
JsonGenerator generator = new JsonGenerator.Options()
    .excludeNulls()
    .dateFormat("yyyy-MM-dd HH:mm:ss")
    .timezone("America/New_York")
    .excludeFieldsByName("password", "secret")
    .excludeFieldsByType(Class.class)
    .disableUnicodeEscaping()
    .build();

Map<String, Object> user = Map.of(
    "name", "Alice",
    "password", "secret123",    // Will be excluded
    "lastLogin", new Date(),
    "metadata", null            // Will be excluded
);

String json = generator.toJson(user);
// {"name":"Alice","lastLogin":"2023-12-01 10:30:45"}

// Custom converter for specific types
JsonGenerator customGenerator = new JsonGenerator.Options()
    .addConverter(LocalDateTime.class, { obj, key ->
        return obj.toString() + "Z";
    })
    .addConverter({ type -> type.getName().startsWith("com.myapp") }, { obj, key ->
        return obj.getId(); // Convert custom objects to just their ID
    })
    .build();

JsonGenerator.Converter Interface

Interface for implementing custom type conversions during JSON generation.

/**
 * Interface for custom type conversion during JSON generation
 */
interface Converter {
    /** Check if this converter handles the given type */
    boolean handles(Class<?> type);
    
    /** Convert the object to a JSON-serializable form */
    Object convert(Object value, String key);
}

DefaultJsonGenerator

Default implementation of JsonGenerator providing full customization support.

/**
 * Default JsonGenerator implementation with full customization support
 */
public class DefaultJsonGenerator implements JsonGenerator {
    // Constructor is package-private, use JsonGenerator.Options.build()
    
    /** Convert object to JSON (implements JsonGenerator) */
    public String toJson(Object object);
    
    /** Check field name exclusion (implements JsonGenerator) */
    public boolean isExcludingFieldsNamed(String name);
    
    /** Check value exclusion (implements JsonGenerator) */
    public boolean isExcludingValues(Object value);
}

Advanced Serialization Patterns

Custom Date Formatting

// Multiple date format scenarios
JsonGenerator usFormat = new JsonGenerator.Options()
    .dateFormat("MM/dd/yyyy HH:mm:ss", Locale.US)
    .timezone("America/Chicago")
    .build();

JsonGenerator isoFormat = new JsonGenerator.Options()
    .dateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
    .timezone("UTC")
    .build();

Date timestamp = new Date();
String usJson = usFormat.toJson(Map.of("created", timestamp));
String isoJson = isoFormat.toJson(Map.of("created", timestamp));

Field Filtering and Security

// Exclude sensitive fields and types
JsonGenerator secureGenerator = new JsonGenerator.Options()
    .excludeFieldsByName("password", "secret", "token", "key")
    .excludeFieldsByType(
        java.security.PrivateKey.class,
        javax.crypto.SecretKey.class
    )
    .excludeNulls()
    .build();

// Safe serialization of user data
Map<String, Object> userData = getUserData();
String safeJson = secureGenerator.toJson(userData);

Complex Type Conversion

// Convert custom business objects
JsonGenerator businessGenerator = new JsonGenerator.Options()
    .addConverter(Money.class, { money, key ->
        return Map.of(
            "amount", money.getAmount().toString(),
            "currency", money.getCurrency().getCurrencyCode()
        );
    })
    .addConverter(Address.class, { address, key ->
        return address.getFormattedAddress();
    })
    .addConverter({ type -> 
        return type.isAnnotationPresent(JsonSerializable.class);
    }, { obj, key ->
        return obj.toJsonMap();
    })
    .build();

Performance Optimization

// Optimized generator for high-throughput scenarios
JsonGenerator optimizedGenerator = new JsonGenerator.Options()
    .disableUnicodeEscaping()  // Faster but less compatible
    .build();

// Reuse generator instances
private static final JsonGenerator SHARED_GENERATOR = 
    new JsonGenerator.Options().excludeNulls().build();

public String toJson(Object obj) {
    return SHARED_GENERATOR.toJson(obj);
}

Error Handling

JSON serialization can fail with various exceptions:

try {
    String json = JsonOutput.toJson(problematicObject);
} catch (StackOverflowError e) {
    // Circular reference detected
    System.err.println("Circular reference in object graph");
} catch (Exception e) {
    // Other serialization errors
    System.err.println("JSON serialization failed: " + e.getMessage());
}

Install with Tessl CLI

npx tessl i tessl/maven-org-apache-groovy--groovy-json

docs

index.md

json-building.md

json-output.md

json-parsing.md

low-level-processing.md

utilities.md

tile.json