Registry / serialization / typescript-json-serializer

typescript-json-serializer

JSON →
library6.0.1jsnpmunverified

typescript-json-serializer is a TypeScript library designed to facilitate the conversion between JavaScript/JSON objects and strongly-typed TypeScript classes. It leverages TypeScript decorators (`@JsonObject`, `@JsonProperty`) to define the serialization and deserialization mapping, allowing for complex nested structures, inheritance, and custom property transformations. The current stable version is 6.0.1, with a consistent release cadence that includes multiple major versions (v4, v5, v6) over a short period, indicating active maintenance and ongoing development. Its key differentiator lies in its declarative, decorator-driven approach, which provides a robust way to manage serialization logic directly within class definitions, including explicit support for enums, dates, and custom type resolvers. It also offers flexible configuration options for error handling, nullish value policies, and property name formatting, distinguishing it from simpler `JSON.parse`/`JSON.stringify` methods or libraries that rely purely on reflection without explicit decorator metadata.

npm install typescript-json-serializer
INSTALL
IMPORT
SIG · TYPESCRIPT-JSON-SE
T
typescript-json-serializer
serializationjavascriptv6.0.1
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

JsonSerializer
import { JsonSerializer } from 'typescript-json-serializer';
import JsonSerializer from 'typescript-json-serializer';
JsonSerializer is a named export, not a default export.
JsonObject
import { JsonObject } from 'typescript-json-serializer';
const { JsonObject } = require('typescript-json-serializer');
Used as a class decorator. Ensure your tsconfig.json enables `experimentalDecorators` and `emitDecoratorMetadata`.
JsonProperty
import { JsonProperty } from 'typescript-json-serializer';
const JsonProperty = require('typescript-json-serializer').JsonProperty;
Used as a property decorator. Allows explicit configuration of property names, types, and requirements.
throwError
import { throwError } from 'typescript-json-serializer';
import * as serializer from 'typescript-json-serializer'; const errorCb = serializer.throwError;
A utility function commonly used as an error callback for the JsonSerializer.

Demonstrates defining classes with `JsonObject` and `JsonProperty` decorators, instantiating `JsonSerializer`, and performing both deserialization from a JSON payload to a TypeScript class instance and serialization back to JSON.

import { JsonSerializer, JsonObject, JsonProperty, throwError } from 'typescript-json-serializer'; // 1. Define your classes using decorators @JsonObject() export class PhoneNumber { @JsonProperty() countryCode: string; @JsonProperty() value: string; } @JsonObject() export class Person { @JsonProperty({required: true}) id: number; @JsonProperty() name: string; @JsonProperty({name: 'dob'}) birthDate: Date; @JsonProperty({type: PhoneNumber}) phone: PhoneNumber; } // 2. Prepare data (e.g., from an API response) const jsonPayload = { id: 123, name: 'John Doe', dob: '1990-05-15T00:00:00.000Z', phone: { countryCode: '+1', value: '555-1234' } }; // 3. Instantiate the serializer const serializer = new JsonSerializer({ errorCallback: throwError, nullishPolicy: { undefined: 'allow', null: 'allow' }, additionalPropertiesPolicy: 'disallow' }); // 4. Deserialize JSON to a class instance try { const personInstance = serializer.deserialize(jsonPayload, Person); console.log('Deserialized Person:', personInstance); console.log('Person name:', personInstance.name); // Access as a class instance console.log('Person phone country code:', personInstance.phone.countryCode); // 5. Serialize a class instance back to JSON const serializedJson = serializer.serialize(personInstance); console.log('Serialized JSON:', serializedJson); } catch (error) { console.error('Serialization/Deserialization Error:', error); } // Ensure your tsconfig.json has: // { // "compilerOptions": { // "emitDecoratorMetadata": true, // "experimentalDecorators": true // } // }
Debug
Known issues
breakingMajor version updates (e.g., v4.x to v5.x, v5.x to v6.x) often introduce breaking changes. Always review the release notes for specific changes, API adjustments, and migration guides when upgrading across major versions to avoid unexpected behavior.
fix
Consult the official GitHub repository's release notes for the specific version you are upgrading to and adjust your code accordingly.
affects: >=4.0.0
gotchaThis library heavily relies on TypeScript's experimental decorator features. You MUST enable `experimentalDecorators` and `emitDecoratorMetadata` in your `tsconfig.json` compiler options for the decorators to function correctly at runtime. Failure to do so will lead to runtime errors during serialization or deserialization.
fix
Add or ensure the following entries in your `tsconfig.json`:
```json
{
    "compilerOptions": {
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true
    }
}
```
affects: >=4.0.0
gotchaFor properties that are complex objects or arrays of complex objects, you often need to explicitly specify the type within the `@JsonProperty` decorator using the `type` option (e.g., `{type: MyClass}` or for arrays `{type: () => MyClass}` for circular dependencies) to ensure correct recursive deserialization.
fix
For nested objects, ensure `@JsonProperty({type: MyNestedClass})` is used. For arrays, use `@JsonProperty({type: () => MyArrayElementClass})` for proper type inference and deserialization.
affects: >=4.0.0
Errors
Common errors & fixes
TypeError: Cannot read properties of undefined (reading 'constructor')
This error frequently occurs when TypeScript's `emitDecoratorMetadata` compiler option is not enabled, preventing the serializer from inferring types at runtime, especially when dealing with nested objects or arrays.
fix
Ensure `emitDecoratorMetadata` and `experimentalDecorators` are set to `true` in your `tsconfig.json` file.
Property 'propertyName' is not deserialized/serialized correctly or is missing.
The property either lacks the `@JsonProperty()` decorator, the class itself isn't decorated with `@JsonObject()`, or a custom `name` mapping in `@JsonProperty({ name: 'jsonKey' })` is incorrect.
fix
Verify that all classes intended for serialization are decorated with `@JsonObject()` and all properties needing to be serialized/deserialized have the `@JsonProperty()` decorator. Check `name` mappings if the JSON key differs from the class property name.
Error: Deserialization error: Required property 'propertyName' is missing.
This typically happens when a JSON payload is missing a property that has been marked as `required: true` in its `@JsonProperty` decorator configuration.
fix
Ensure that the incoming JSON data contains all properties marked as `required: true`. Alternatively, adjust the `required` setting in `@JsonProperty` if the property is not strictly mandatory.
Upgrade
Version history
6.0.1latest on npm
Audit
Dependencies

No dependency data recorded yet.

Agent activity
9 hits · last 30 days
node
8
OpenAI (training)
1
Resources
typescript-json-serializer — npm install typescript-json-serializer · libregistry