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.
📋 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
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:
Best Practice: Always quote struct keys if you need exact casing in JSON output, especially for REST APIs and JavaScript interoperability.
📊 Query Serialization
Queries can be serialized in three different formats using the queryFormat argument:
🎯 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" ) |
Best Practice: Use property-level @jsonExclude( true ) for individual fields and class-level @jsonExclude( "field1,field2" ) with a comma-separated list for multiple fields. Implement custom toJSON() methods for complex transformation logic.
📥 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 introspectionBoxQuerySerializer- Handles query objects with format optionsBoxStructSerializer- Handles structs and mapsBoxArraySerializer- Handles arrays and listsDynamicObjectSerializer- Handles Java object proxiesExceptionSerializer- Handles exception objectsJavaArraySerializer- 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 serializequeryFormat(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 parsestrictMapping(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
✅ Always quote struct keys for exact casing in JSON output
✅ Use
isJSON()validation before deserializing user input✅ Implement custom
toJSON()methods for complex class serialization logic✅ Use
jsonExcludeannotations to protect sensitive data (passwords, secrets)✅ Prefer
pretty: truefor configuration files and debugging✅ Use
queryFormat="struct"for REST API responses (most compatible with JavaScript)✅ Handle JSON errors gracefully with try/catch blocks
✅ Validate API responses with
isJSON()before parsing✅ Use member methods (
toJSON(),fromJSON()) for cleaner, more readable code✅ Document serialization behavior in class comments when using custom logic
🔗 Related Documentation
StructuresArraysQueriesClasses & O.O.Last updated
Was this helpful?
