{"id":12239,"library":"typescript-json-serializer","title":"TypeScript JSON Serializer","description":"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.","status":"active","version":"6.0.1","language":"javascript","source_language":"en","source_url":"https://github.com/GillianPerard/typescript-json-serializer","tags":["javascript","json","typescript","serializer","deserializer","decorator","metadata"],"install":[{"cmd":"npm install typescript-json-serializer","lang":"bash","label":"npm"},{"cmd":"yarn add typescript-json-serializer","lang":"bash","label":"yarn"},{"cmd":"pnpm add typescript-json-serializer","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"JsonSerializer is a named export, not a default export.","wrong":"import JsonSerializer from 'typescript-json-serializer';","symbol":"JsonSerializer","correct":"import { JsonSerializer } from 'typescript-json-serializer';"},{"note":"Used as a class decorator. Ensure your tsconfig.json enables `experimentalDecorators` and `emitDecoratorMetadata`.","wrong":"const { JsonObject } = require('typescript-json-serializer');","symbol":"JsonObject","correct":"import { JsonObject } from 'typescript-json-serializer';"},{"note":"Used as a property decorator. Allows explicit configuration of property names, types, and requirements.","wrong":"const JsonProperty = require('typescript-json-serializer').JsonProperty;","symbol":"JsonProperty","correct":"import { JsonProperty } from 'typescript-json-serializer';"},{"note":"A utility function commonly used as an error callback for the JsonSerializer.","wrong":"import * as serializer from 'typescript-json-serializer'; const errorCb = serializer.throwError;","symbol":"throwError","correct":"import { throwError } from 'typescript-json-serializer';"}],"quickstart":{"code":"import { JsonSerializer, JsonObject, JsonProperty, throwError } from 'typescript-json-serializer';\n\n// 1. Define your classes using decorators\n@JsonObject()\nexport class PhoneNumber {\n    @JsonProperty() countryCode: string;\n    @JsonProperty() value: string;\n}\n\n@JsonObject()\nexport class Person {\n    @JsonProperty({required: true}) id: number;\n    @JsonProperty() name: string;\n    @JsonProperty({name: 'dob'}) birthDate: Date;\n    @JsonProperty({type: PhoneNumber}) phone: PhoneNumber;\n}\n\n// 2. Prepare data (e.g., from an API response)\nconst jsonPayload = {\n    id: 123,\n    name: 'John Doe',\n    dob: '1990-05-15T00:00:00.000Z',\n    phone: {\n        countryCode: '+1',\n        value: '555-1234'\n    }\n};\n\n// 3. Instantiate the serializer\nconst serializer = new JsonSerializer({\n    errorCallback: throwError,\n    nullishPolicy: {\n        undefined: 'allow',\n        null: 'allow'\n    },\n    additionalPropertiesPolicy: 'disallow'\n});\n\n// 4. Deserialize JSON to a class instance\ntry {\n    const personInstance = serializer.deserialize(jsonPayload, Person);\n    console.log('Deserialized Person:', personInstance);\n    console.log('Person name:', personInstance.name); // Access as a class instance\n    console.log('Person phone country code:', personInstance.phone.countryCode);\n\n    // 5. Serialize a class instance back to JSON\n    const serializedJson = serializer.serialize(personInstance);\n    console.log('Serialized JSON:', serializedJson);\n} catch (error) {\n    console.error('Serialization/Deserialization Error:', error);\n}\n\n// Ensure your tsconfig.json has:\n// {\n//   \"compilerOptions\": {\n//     \"emitDecoratorMetadata\": true,\n//     \"experimentalDecorators\": true\n//   }\n// }\n","lang":"typescript","description":"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."},"warnings":[{"fix":"Consult the official GitHub repository's release notes for the specific version you are upgrading to and adjust your code accordingly.","message":"Major 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.","severity":"breaking","affected_versions":">=4.0.0"},{"fix":"Add or ensure the following entries in your `tsconfig.json`:\n```json\n{\n    \"compilerOptions\": {\n        \"emitDecoratorMetadata\": true,\n        \"experimentalDecorators\": true\n    }\n}\n```","message":"This 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.","severity":"gotcha","affected_versions":">=4.0.0"},{"fix":"For nested objects, ensure `@JsonProperty({type: MyNestedClass})` is used. For arrays, use `@JsonProperty({type: () => MyArrayElementClass})` for proper type inference and deserialization.","message":"For 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.","severity":"gotcha","affected_versions":">=4.0.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Ensure `emitDecoratorMetadata` and `experimentalDecorators` are set to `true` in your `tsconfig.json` file.","cause":"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.","error":"TypeError: Cannot read properties of undefined (reading 'constructor')"},{"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.","cause":"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.","error":"Property 'propertyName' is not deserialized/serialized correctly or is missing."},{"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.","cause":"This typically happens when a JSON payload is missing a property that has been marked as `required: true` in its `@JsonProperty` decorator configuration.","error":"Error: Deserialization error: Required property 'propertyName' is missing."}],"ecosystem":"npm"}