JSON

Powerful JSON serialization and deserialization with automatic class conversion and custom formatting

BoxLang provides comprehensive JSON (JavaScript Object Notation) support with automatic serialization of BoxLang data types, including classes, queries, arrays, structs, and more. The JSON engine is built on Jackson Jr and includes custom serializers for BoxLang-specific types.

Built on Jackson Jr: BoxLang uses the high-performance Jackson Jr library with custom serializers and deserializers for BoxLang types. This ensures fast, reliable JSON processing with full control over the serialization format.

📋 Table of Contents

💻 JSON in Code

Let's explore JSON operations with practical examples:

// Create complex data structure
user = {
    id: 1,
    name: "Alice Johnson",
    email: "[email protected]",
    active: true,
    roles: [ "admin", "developer" ],
    metadata: {
        lastLogin: now(),
        preferences: { theme: "dark", language: "en" }
    }
};

// Serialize to JSON
json = user.toJSON();
println( json );

// Pretty print for readability
prettyJson = jsonSerialize( user, pretty: true );
println( prettyJson );

// Deserialize back to BoxLang data
restored = json.fromJSON();
println( "Name: " & restored.name );

// Validate JSON
if ( isJSON( json ) ) {
    println( "Valid JSON!" );
}

// List to JSON
tags = "programming,boxlang,json,tutorial";
jsonTags = tags.listToJSON();
println( jsonTags ); // ["programming","boxlang","json","tutorial"]

📚 JSON Built-In Functions (BIFs)

BoxLang provides JSON BIFs that can be called as functions or member methods on compatible types.

Core JSON Functions

Function
Purpose
Member Method Available

jsonSerialize()

Convert data to JSON string

toJSON() on most types

jsonDeserialize()

Parse JSON string to data

fromJSON() on strings

isJSON()

Validate JSON string

No

jsonPrettify()

Format JSON for readability

jsonPrettify() on strings

Member Method Support

The toJSON() member method is available on:

  • Structs - myStruct.toJSON()

  • Arrays - myArray.toJSON()

  • Queries - myQuery.toJSON()

  • Classes - myClass.toJSON() (with automatic property serialization)

  • Numbers - 123.toJSON()

  • Booleans - true.toJSON()

  • Strings - "text".listToJSON() (converts list to JSON array)

The fromJSON() member method is available on:

  • Strings - jsonString.fromJSON()

📤 JSON Serialization (jsonSerialize / toJSON)

Convert any BoxLang data to JSON format using jsonSerialize() or the toJSON() member method.

Basic Serialization

Supported Data Types

BoxLang automatically serializes all native types:

🎨 Pretty Printing

Format JSON with indentation for readability:

🔑 Key Casing Preservation

BoxLang preserves the exact casing of struct keys in JSON:

📊 Query Serialization

Queries can be serialized in three different formats using the queryFormat argument:

Default Format: Queries serialize as arrays of structs (queryFormat="struct") when no format is specified. This is the most common format for REST APIs.

🎯 Class Serialization (The Magic!)

BoxLang makes it incredibly easy to serialize classes to JSON with automatic property introspection. The BoxClassSerializer intelligently converts class instances to JSON by examining their properties and respecting serialization annotations.

Automatic Property Serialization

🔒 Controlling Serialization with Annotations

Use annotations to control what gets serialized:

🎨 Custom toJSON() Method

Override serialization completely with your own toJSON() method:

🔄 Recursive Class Handling

BoxLang automatically handles recursive class references:

📋 Class Serialization Annotations Reference

| Annotation | Scope | Purpose | Example | |------------|-------|---------|---------|------| | @serializable | Class/Property | Enable/disable serialization | @serializable( false ) | | @jsonExclude | Class/Property | Exclude from JSON | @jsonExclude( true ) | | @jsonExclude (list) | Class | Exclude multiple properties | @jsonExclude( "password,secret" ) |

How It Works: The BoxClassSerializer introspects the class's property definitions, filters out excluded properties, and serializes the variables scope values. Only properties defined with the property keyword are included in serialization.

📥 JSON Deserialization (jsonDeserialize / fromJSON)

Parse JSON strings back into BoxLang data structures using jsonDeserialize() or the fromJSON() member method.

Basic Deserialization

Strict Mapping Mode

Control how JSON objects are mapped to BoxLang types:

Supported JSON Types

BoxLang deserializes JSON to native types:

Validation Before Deserialization

Always validate JSON before deserializing:

✅ JSON Validation (isJSON)

Test if a string contains valid JSON:

📝 List to JSON Conversion

Convert delimited strings (lists) to JSON arrays:

🎯 Advanced JSON Techniques

Working with API Responses

JSON Configuration Files

Nested Data Transformation

JSON Stream Processing

🔧 Custom Serializers (Advanced)

BoxLang uses custom serializers for specific types. You can examine these in the BoxLang source:

  • BoxClassSerializer - Handles class instances with property introspection

  • BoxQuerySerializer - Handles query objects with format options

  • BoxStructSerializer - Handles structs and maps

  • BoxArraySerializer - Handles arrays and lists

  • DynamicObjectSerializer - Handles Java object proxies

  • ExceptionSerializer - Handles exception objects

  • JavaArraySerializer - Handles native Java arrays

These serializers are automatically invoked when their respective types are encountered during JSON serialization.

📖 Function Reference

jsonSerialize( data, [queryFormat], [useSecureJSONPrefix], [useCustomSerializer], [pretty] )

Convert BoxLang data to JSON string.

Arguments:

  • data (any, required) - Data to serialize

  • queryFormat (string) - Query format: "struct", "row", "column", "true", "false" (default: "row")

  • useSecureJSONPrefix (string/boolean) - Add secure prefix (not implemented)

  • useCustomSerializer (boolean) - Use custom serializer (not implemented)

  • pretty (boolean) - Pretty print with indentation (default: false)

Returns: String (JSON)

Member Methods:

  • data.toJSON() - Available on most types

  • "list,items".listToJSON() - Convert delimited string to JSON array

jsonDeserialize( json, [strictMapping], [useCustomSerializer] )

Parse JSON string to BoxLang data.

Arguments:

  • json (string, required) - JSON string to parse

  • strictMapping (boolean) - Force all objects to structs (default: true)

  • useCustomSerializer (string) - Custom serializer name (not implemented)

Returns: Any (native BoxLang types)

Member Methods:

  • jsonString.fromJSON() - Parse JSON string

isJSON( var )

Validate if string is valid JSON.

Arguments:

  • var (any, required) - Value to test

Returns: Boolean

jsonPrettify( var )

Format JSON string with indentation.

Arguments:

  • var (string, required) - JSON string to format

Returns: String (formatted JSON)

Member Methods:

  • jsonString.jsonPrettify() - Format JSON string

🎓 Best Practices

  1. Always quote struct keys for exact casing in JSON output

  2. Use isJSON() validation before deserializing user input

  3. Implement custom toJSON() methods for complex class serialization logic

  4. Use jsonExclude annotations to protect sensitive data (passwords, secrets)

  5. Prefer pretty: true for configuration files and debugging

  6. Use queryFormat="struct" for REST API responses (most compatible with JavaScript)

  7. Handle JSON errors gracefully with try/catch blocks

  8. Validate API responses with isJSON() before parsing

  9. Use member methods (toJSON(), fromJSON()) for cleaner, more readable code

  10. Document serialization behavior in class comments when using custom logic

StructuresArraysQueriesClasses & O.O.

Last updated

Was this helpful?