How to use TypeScript Decorators for Serialization In JSON

TypeScript decorators offer a declarative approach to modify the behavior of class declarations and members. For serialization, decorators can be utilized to annotate properties that require special handling or to automatically manage serialization without explicitly calling serialization logic in business code.

Step 1: Enable Decorators in TypeScript Configuration First, ensure your TypeScript project is set up to use decorators. Modify the tsconfig.json file to enable the experimentalDecorators option:

JavaScript
{
    "compilerOptions": {
        "target": "ES5",
        "experimentalDecorators": true
    }
}

Step 2: Define Serialization Decorators Create custom decorators to handle serialization logic for different types of properties. For example, you might have a decorator for formatting dates or excluding properties from the serialized output.

JavaScript
function SerializeDate(target: any, propertyKey: string) {
    let value: Date;

    const getter = function() {
        return value ? value.toISOString() : null;
    };

    const setter = function(newVal: Date) {
        value = newVal;
    };

    Object.defineProperty(target, propertyKey, {
        get: getter,
        set: setter,
        enumerable: true,
        configurable: true
    });
}

function ExcludeFromSerialization(target: any, propertyKey: string) {
    Object.defineProperty(target, propertyKey, {
        enumerable: false,
        configurable: true
    });
}


Step 3: Define the Interface and Class Implement a class that uses these decorators, ensuring properties are handled according to the defined serialization rules.

JavaScript
interface Course {
    courseName: string;
    courseFees: number;
    startDate: Date;
}

class CourseImplementation implements Course {
    @ExcludeFromSerialization
    courseId: number;

    courseName: string;
    courseFees: number;

    @SerializeDate
    startDate: Date;

    constructor(courseId: number, name: string, fees: number, startDate: Date) {
        this.courseId = courseId;
        this.courseName = name;
        this.courseFees = fees;
        this.startDate = startDate;
    }
}

Step 4: Create an Instance and Serialize Instantiate your class and serialize it using JSON.stringify, which will now respect the decorators’ behavior.

JavaScript
const course = new CourseImplementation(101, "JavaScript", 30000, new Date("2024-03-01"));
const serializedCourse = JSON.stringify(course);
console.log(serializedCourse);


Output:

{
"courseName": "JavaScript",
"courseFees": 30000,
"startDate": "2024-03-01T00:00:00.000Z"
}




How to Convert an Object to a JSON String in Typescript ?

In TypeScript, an object is a collection of related data and functionality. Objects are made up of properties and methods. Properties describe the object, methods describe what it can do.

Table of Content

  • Using JSON.stringify()
  • Using json-stringify-safe library
  • Using a Custom Serialization Function
  • Using TypeScript Decorators for Serialization

Similar Reads

Using JSON.stringify()

Define an interface Course that describes the shape of the object with the required properties and their types.Declare the course variable with the Course type. This ensures the object matches the interface shape.Assign the object literal to the course – TypeScript will check it matches the interface.Call JSON.stringify() on the typed object....

Using json-stringify-safe library

Steps to use JSON-stringify-safe library with TypeScript:...

Using a Custom Serialization Function

In some cases, you may have complex objects with nested structures or non-serializable properties that need special handling when converting to JSON. In such scenarios, you can define a custom serialization function to handle the conversion process....

Using TypeScript Decorators for Serialization

TypeScript decorators offer a declarative approach to modify the behavior of class declarations and members. For serialization, decorators can be utilized to annotate properties that require special handling or to automatically manage serialization without explicitly calling serialization logic in business code....

Contact Us