Serializer utilities
This contains a comprehensive JSON serialization and deserialization solution, designed to support complex data structures, including those involving big integers and custom object types, ensuring robust and flexible handling of JSON data.
Key features
customNumberParser
Function: Enhances the parsing of numeric values, supporting safe integers, floating-point numbers, and BigInt values.JSONSerializer
Interface: Defines methods for serializing objects to JSON strings and deserializing JSON strings to JavaScript objects, with support for HTTP response objects and message event data.DefaultJSONSerializer
Class: Implements theJSONSerializer
interface, providing default serialization and deserialization behaviors that can be customized via theJSONSerializerConfig
.JSONReplacer
andJSONReviver
Functions: Facilitate custom serialization and deserialization processes, allowing for the handling of special types, such as dates and NaN values, and the exclusion of properties with specific key prefixes.
Examples
JSON serialization/deserialization
The JSONSerializer
DI Token enables the serialization and deserialization of complex objects, including BigInt values and custom object types, ensuring that JSON data is accurately represented in JavaScript.
import { JSONSerializer } from '@genesislcap/foundation-utils';
import { GenesisElement } from '@genesislcap/web-core';
export class MyService extends GenesisElement {
@JSONSerializer serializer!: JSONSerializer; // DI token
const object = { date: new Date(), bigNumber: BigInt(12345678901234567890) };
const jsonString = serializer.serialize(object);
console.log(jsonString); // Outputs a JSON string with custom formatting
const parsedObject = serializer.deserialize(jsonString);
console.log(parsedObject); // Outputs the original object with date and bigNumber correctly parsed
}
Configuring the serializer
You can customize the default serializer behaviour by providing a JSONSerializerConfig
instance, which defines custom parsing and stringifying logic, including the handling of BigInt values and special object types.
Custom number parsing
The customNumberParser
function is crucial for correctly handling numerical values during deserialization, ensuring that numbers are accurately represented in the resulting JavaScript objects.
import { customNumberParser } from '@genesislcap/foundation-utils';
const parsedNumber = customNumberParser("12345678901234567890");
console.log(parsedNumber); // Outputs a BigInt
Key points
- Use the serializer and parser utilities for consistent handling of JSON data, especially when dealing with large numbers or custom object types.
- Use the DI system to manage serializer instances, ensuring that custom configurations are centrally managed and easily accessible.
- Employ the
JSONReplacer
andJSONReviver
functions for custom serialization and deserialization needs, such as handling dates or excluding private properties.