JIYIK CN >

Current Location:Home > Learning > PROGRAM > TypeScript >

Convert JSON object to a class in TypeScript

Author:JIYIK Last Updated:2025/04/15 Views:

Data on the internet flows in the form of strings, which can be converted into a very popular format called JSON. The JSON representation of this data usually represents an object or even a class in TypeScript.

TypeScript provides the ability to convert objects into classes. This article will discuss how to convert received objects into TypeScript classes to make type support, IDE completion, and other features accessible.

Object.assignConvert from JSON to class in TypeScript

Object.assignThe method provides an easy way to convert a JSON object to a TypeScript class so that the methods associated with that class can also be accessed.

The following code snippet shows how to use Object.assignthe method to convert a JSON object to a TypeScript class.

Code:

class Animal{
    name : string;
    legs : number;
    eyes : number;
    constructor(name? : string, legs? : number, eyes? : number){

        this.name = name ?? 'Default name';
        this.legs = legs ?? 0;
        this.eyes = eyes ?? 0;
    }

    getName(){
        return this.name;
    }

    getEyes(){
        return this.eyes;
    }
}

var jsonString : string = `{
    "name" : "Tiger",
    "legs" : 4,
    "eyes" : 2
}`

var animalObj =  new Animal();
console.log(animalObj.getEyes());
Object.assign(animalObj, JSON.parse(jsonString));
console.log(animalObj.getEyes());

Output:

0
2

In the above example, getEyes()the method returns 0, which is the default value, and when the parsed JSON object is assigned to animalObjthe object, it returns 2, the value in the JSON string.

Convert JSON string to class using custom method in TypeScript

A JSON object can fromJSONbe converted to the corresponding class in TypeScript using a custom method such as This approach is more useful as it provides more power to the user.

Code:

class Animal{
    name : string;
    legs : number;
    eyes: number;
    constructor(name : string, legs : number, eyes: number){
        this.name = name;
        this.legs = legs;
        this.eyes = eyes;
    }

    getName(){
        return this.name;
    }

    toObject(){
        return {
            name : this.name,
            legs : this.legs.toString(),
            eyes : this.eyes.toString()
        }
    }

    serialize() {
        return JSON.stringify(this.toObject());
    }

    static fromJSON(serialized : string) : Animal {
        const animal : ReturnType<Animal["toObject"]> = JSON.parse(serialized);

        return new Animal(
            animal.name,
            animal.legs,
            animal.eyes
        )
    }
}

var jsonString : string = `{
    "name" : "Tiger",
    "legs" : 4,
    "eyes" : 2
}`

var animalObj : Animal = Animal.fromJSON(jsonString);
console.log(animalObj)
// this will work now
console.log(animalObj.getName());

Output:

Animal: {
    "name": "Tiger",
    "legs": 4,
    "eyes": 2
}
"Tiger"

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

Handling exceptions with try..catch..finally in TypeScript

Publish Date:2025/04/15 Views:170 Category:TypeScript

This article will discuss try..catch..finally handling exceptions in TypeScript using the statement. Handling exceptions in TypeScript In TypeScript, try..catch..finally a block handles exceptions that occur during program runtime. It allow

在 TypeScript 中返回一个 Promise

Publish Date:2023/03/19 Views:590 Category:TypeScript

本教程讨论如何在 TypeScript 中返回正确的 Promise。这将提供 TypeScript 中 Returns Promise 的完整编码示例,并完整演示每个步骤。

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial