Download the PHP package farzai/json-serializer without Composer
On this page you can find all versions of the php package farzai/json-serializer. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download farzai/json-serializer
More information about farzai/json-serializer
Files in farzai/json-serializer
Package json-serializer
Short Description High-performance JSON serializer for PHP with streaming support, type-safe object mapping, and memory-efficient processing.
License MIT
Homepage https://github.com/parsilver/json-serializer-php
Informations about the package json-serializer
JSON Serializer for PHP
A high-performance, type-safe JSON serializer and deserializer for PHP 8.1+ with advanced features including attribute-based configuration, nested object support, versioning, transformers, and comprehensive error handling.
Installation
You can install the package via composer:
Features
- High Performance - Optimized for speed and memory efficiency
- Generator Support - Memory-efficient serialization of large datasets using PHP generators
- Type-Safe - Full PHP 8.1+ type system support including union types
- Nested Objects - Automatic recursive serialization/deserialization
- Collections -
array<Type>notation for typed collections - Attributes - Powerful attribute-based configuration
- Versioning - API versioning with
#[Since]and#[Until] - Transformers - Custom transformers for DateTime, Enums, and more
- Naming Strategies - snake_case, camelCase, PascalCase, kebab-case
- Virtual Properties - Computed properties from methods
- Error Handling - Detailed error messages with property paths
- Circular Reference Detection - Automatic detection and prevention
- Max Depth Control - Configurable depth limits
- Type Coercion - STRICT, SAFE, and LENIENT modes for flexible type handling
When to Use This Library
✅ Use This Library When:
- Type-Safe Object Mapping: You need to deserialize JSON into strongly-typed PHP objects
- API Versioning: Your API supports multiple versions with
#[Since]and#[Until]attributes - Large File Processing: You need to process JSON files > 100MB without memory issues
- Advanced Features: You need transformers, virtual properties, or custom naming strategies
- Attribute-Based Config: You prefer declarative configuration over imperative code
- Streaming Operations: You need to process JSON incrementally or extract specific paths
⚠️ Use Native Functions When:
- Simple Arrays: Basic
json_encode(['key' => 'value'])for simple data structures - Maximum Performance: Serialization speed is critical and you don't need advanced features
- Small Data: Processing < 1KB of data where overhead doesn't matter
- No Type Safety Needed: You're comfortable working with untyped arrays
Performance Trade-offs
Serialization: ~50-60x slower than native json_encode due to rich features
- Native: 1.0μs for small data, 3.6ms for 10MB
- This library: 49μs for small data, 204ms for 10MB
- Recommendation: Use native functions for hot paths where features aren't needed
Deserialization: Competitive with native json_decode (~1.0x speed)
- Native: 942μs for 1MB, 9.9ms for 10MB
- This library: 936μs for 1MB, 10.0ms for 10MB
- Recommendation: Safe to use everywhere for deserialization with type-safe object mapping
Memory: Only ~7% overhead compared to native functions
Usage
Basic Serialization
Basic Deserialization
Nested Objects & Collections
Attributes
Versioning
Custom Transformers
Union Types
Error Handling
Circular Reference Detection
The library automatically detects and prevents circular references during serialization:
Builder Pattern
Security & Configuration
Protect your application from malicious or malformed JSON with built-in security features:
Security Best Practices:
- Always set a reasonable
maxDepthlimit (default: 512) - Keep circular reference detection enabled for untrusted data
- Use strict types mode when deserializing external data
- Validate data structure before deserialization for critical applications
Type Coercion Modes
Control how the deserializer handles type mismatches with three coercion modes:
Coercion Rules
STRICT Mode:
- No type coercion
- int → float (safe widening)
- Throws exception on any other mismatch
SAFE Mode (Default):
- Numeric strings → numbers ("123" → 123)
- Boolean strings → bool ("true" → true, "false" → false)
- 1/0 → boolean
- int → float
- Whole number floats → int (42.0 → 42)
LENIENT Mode:
- Any value → string (cast)
- Numeric-like → numbers ("abc123" → 123)
- Truthy/falsy → bool ("yes"/"no", non-empty strings)
- Very permissive conversions
Custom Type Handlers
Extend the serializer with custom type handlers for specialized serialization logic:
Use Cases for Custom Type Handlers:
- Special formatting for value objects (Money, Email, UUID)
- Custom serialization for third-party library objects
- Encryption/decryption during serialization
- Legacy data format compatibility
- Performance optimization for specific types
PSR-16 Cache Support
Improve performance by caching metadata with any PSR-16 compatible cache:
Compatible Cache Libraries:
- Symfony Cache
- Laravel Cache (via PSR-16 adapter)
- Doctrine Cache
- Any PSR-16 Simple Cache implementation
Performance Impact:
- First serialization: ~5-10% slower (cache write)
- Subsequent serializations: ~30-50% faster (cache hit)
- Recommended for applications serializing many instances of the same class
Streaming & Large Files
For processing large JSON files without loading everything into memory, use the streaming API:
Streaming Deserialization
Lazy Iterator
Process large JSON arrays with on-demand deserialization:
Path-based Extraction
Extract specific data without parsing the entire JSON:
Memory-Efficient Processing
Generator Serialization
Serialize large datasets memory-efficiently using PHP generators:
Benefits of Generator Serialization:
- Constant Memory Usage: Only one item in memory at a time
- Database Streaming: Fetch and serialize rows without buffering
- Lazy Evaluation: Generate data on-demand during serialization
- Large Datasets: Process millions of records without memory issues
When to Use Generators:
- Serializing database query results (1,000+ rows)
- Processing large CSV files or API responses
- Building JSON from expensive computations
- Any scenario where data doesn't fit comfortably in memory
Performance
The library has been benchmarked against native json_encode/decode functions using PHPBench. Benchmarks run on PHP 8.1+ with comparable results across versions.
Note: This library prioritizes features and type safety over raw speed. The performance overhead is justified by capabilities like attribute-based configuration, versioning, transformers, and streaming support. For simple use cases where these features aren't needed, native
json_encode/decodefunctions are recommended.
Serialization Performance
| Data Size | Native | JsonSerializer | Ratio | Notes |
|---|---|---|---|---|
| Small (<1KB) | 1.0μs | 49.3μs | ~49x slower | Overhead negligible for small data |
| 1MB | 325μs | 20.3ms | ~62x slower | Rich feature set trade-off |
| 5MB | 1.7ms | 101.7ms | ~60x slower | Consistent overhead ratio |
| 10MB | 3.6ms | 204.6ms | ~57x slower | Scales linearly |
Deserialization Performance
| Data Size | Native | JsonSerializer | Ratio | Notes |
|---|---|---|---|---|
| 1MB | 942μs | 936μs | Competitive | Same speed as native! |
| 5MB | 4.9ms | 4.8ms | Competitive | Same speed as native! |
| 10MB | 9.9ms | 10.0ms | Competitive | Same speed as native! |
Object Hydration Performance
| Operation | Time | Notes |
|---|---|---|
| Decode to Class (1MB) | 1.1ms | Minimal overhead for object mapping |
| Decode to Class (5MB) | 5.5ms | Scales linearly with data size |
| Nested Objects | 36μs | Fast recursive hydration |
Memory Usage
| Operation | Memory Peak | Notes |
|---|---|---|
| Native (10MB) | 32.5MB | Baseline |
| JsonSerializer (10MB) | 34.9MB | ~7% overhead |
| Streaming (10MB) | 34.9MB | Constant memory with file operations |
Key Findings
Deserialization: JsonSerializer achieves native-level performance for deserialization, making it ideal for API consumption and data processing.
Serialization: While slower than native for encoding, the overhead is justified by the rich feature set:
- Attribute-based configuration
- Type transformers
- API versioning
- Virtual properties
- Custom naming strategies
Memory Efficiency: Memory usage is comparable to native functions with only ~7% overhead for medium to large datasets.
Running Benchmarks
Troubleshooting
Common Issues and Solutions
Memory Limit Errors
Type Mismatch Errors
Circular Reference Errors
Performance Issues
Max Depth Exceeded
Performance Optimization Tips
- Use PSR-16 Cache: Cache metadata for classes you serialize frequently
- Stream Large Files: Use
iterateFile()for files > 100MB - Disable Unused Features: Turn off circular reference detection if not needed
- Use Native for Simple Data: Reserve this library for complex object mapping
- Batch Processing: Process multiple objects in batches with streaming
Getting Help
- GitHub Issues: Report bugs or request features
- Documentation: Check the examples in this README
- Stack Overflow: Tag your question with
farzai-json-serializer
Testing
Changelog
Please see CHANGELOG for more information on what has changed recently.
Contributing
Please see CONTRIBUTING for details.
Security Vulnerabilities
Please review our security policy on how to report security vulnerabilities.
Credits
- parsilver
- All Contributors
License
The MIT License (MIT). Please see License File for more information.