如何在TypeScript類中轉換JSON物件?


在TypeScript中,在類內部轉換JSON物件是一種將JSON資料對映到結構化TypeScript物件的實用技術。透過顯式定義型別,我們可以確保型別安全並無縫訪問JSON物件的屬性。在本教程中,我們將指導您完成在TypeScript類內部轉換JSON物件的流程,使使用者能夠充分利用TypeScript靜態型別的強大功能。

語法

使用者可以按照以下語法在TypeScript類中建立JSON物件的轉換。

class MyClass {
   // Define class properties
   property1: string;
   property2: number;
   constructor(json: any) {

      // Cast the JSON object to the class type
      const castedJson = json as MyClass;

      // Assign properties from the JSON object
      this.property1 = castedJson.property1;
      this.property2 = castedJson.property2;
   }
}

在上述語法中,我們建立了一個名為MyClass的類,它具有型別為字串的property1屬性和型別為數字的property2屬性。建構函式接受一個型別為any的引數json,表示JSON物件。

在建構函式內部,使用關鍵字將json物件轉換,表明它應該被視為MyClass的例項。然後將castedJson的屬性分配給類的相應屬性。

示例1

在這個例子中,我們定義了Person類,其中包含姓名、年齡和電子郵件的屬性。建構函式接受一個型別為any的引數json,表示JSON物件。

之後,我們使用型別斷言將json物件轉換為Person類的例項。然後將castedJson物件的屬性分配給類的相應屬性。

接下來,我們在Person類中定義了一個名為displayDetails()的方法。此方法透過將它們記錄到控制檯來顯示人員的姓名、年齡和電子郵件。

最後,我們建立一個名為jsonData的JSON物件,表示一個人的詳細資訊。我們透過將jsonData傳遞給建構函式來建立名為person的Person類例項。然後,我們呼叫person物件上的displayDetails()方法來訪問和顯示人員的詳細資訊。

// Define the Person class
class Person {
   name: string;
   age: number;
   email: string;
   constructor(json: any) {
      const castedJson = json as Person;
      this.name = castedJson.name;
      this.age = castedJson.age;
      this.email = castedJson.email;
   }

   displayDetails() {
      console.log(`Name: ${this.name}`);
      console.log(`Age: ${this.age}`);
      console.log(`Email: ${this.email}`);
   }
}

// Creating a JSON object representing a person
const jsonData = {
   "name": "John Doe",
   "age": 30,
   "email": "johndoe@example.com"
};

// Creating an instance of the Person class
const person = new Person(jsonData);

// Accessing and displaying the person's details
person.displayDetails();

編譯後,它將生成以下JavaScript程式碼:

// Define the Person class
var Person = /** @class */ (function () {
   function Person(json) {
      var castedJson = json;
      this.name = castedJson.name;
      this.age = castedJson.age;
      this.email = castedJson.email;
   }
   Person.prototype.displayDetails = function () {
      console.log("Name: ".concat(this.name));
      console.log("Age: ".concat(this.age));
      console.log("Email: ".concat(this.email));
   };
   return Person;
}());

// Creating a JSON object representing a person
var jsonData = {
   "name": "John Doe",
   "age": 30,
   "email": "johndoe@example.com"
};

// Creating an instance of the Person class
var person = new Person(jsonData);

// Accessing and displaying the person's details
person.displayDetails();

輸出

上述程式碼將產生以下輸出:

Name: John Doe
Age: 30
Email: johndoe@example.com

示例2

在這個例子中,我們定義了一個TypeScript類Employee來表示員工。該類具有姓名、職位和薪水的屬性。建構函式接受一個型別為any的引數json,表示JSON物件。

透過使用型別斷言將json物件轉換為Employee類的例項,我們確保JSON物件被視為員工物件。

我們還有一個calculateAnnualBonus()方法,它根據員工的薪水計算員工的年度獎金。在這個例子中,我們假設固定獎金百分比為10%。

displayEmployeeSummary()方法提供了員工詳細資訊的互動式摘要。它展示了員工的姓名、職位、薪水(以正確的貨幣符號格式化)和計算出的年度獎金(也以正確的貨幣符號格式化)。

然後,我們建立一個名為jsonData的JSON物件,表示員工的詳細資訊。

透過建立一個名為employee的Employee類例項並將jsonData傳遞給建構函式,我們將JSON物件轉換為Employee類。

最後,我們呼叫employee物件上的displayEmployeeSummary()方法來訪問和顯示員工的摘要。

class Employee {
   name: string;
   position: string;
   salary: number;
   constructor(json: any) {
      const castedJson = json as Employee;

      this.name = castedJson.name;
      this.position = castedJson.position;
      this.salary = castedJson.salary;
   }
   calculateAnnualBonus(): number {
      const bonusPercentage = 0.1; // 10% bonus
      const bonusAmount = this.salary * bonusPercentage;
      return bonusAmount;
   }
   displayEmployeeSummary() {
      console.log(`Name: ${this.name}`);
      console.log(`Position: ${this.position}`);
      console.log(`Salary: $${this.salary.toLocaleString()}`);
      console.log(`Annual Bonus: $${this.calculateAnnualBonus().toLocaleString()}`);
   }
}

// Creating a JSON object representing an employee
const jsonData = {
   "name": "John Smith",
   "position": "Senior Developer",
   "salary": 80000
};

// Creating an instance of the Employee class
const employee = new Employee(jsonData);
 
// Displaying the employee summary
employee.displayEmployeeSummary();

編譯後,它將生成以下JavaScript程式碼:

var Employee = /** @class */ (function () {
   function Employee(json) {
      var castedJson = json;
      this.name = castedJson.name;
      this.position = castedJson.position;
      this.salary = castedJson.salary;
   }
   Employee.prototype.calculateAnnualBonus = function () {
      var bonusPercentage = 0.1; // 10% bonus
      var bonusAmount = this.salary * bonusPercentage;
      return bonusAmount;
   };
   Employee.prototype.displayEmployeeSummary = function () {
      console.log("Name: ".concat(this.name));
      console.log("Position: ".concat(this.position));
      console.log("Salary: $".concat(this.salary.toLocaleString()));
      console.log("Annual Bonus: $".concat(this.calculateAnnualBonus().toLocaleString()));
   };
   return Employee;
}());

// Creating a JSON object representing an employee
var jsonData = {
   "name": "John Smith",
   "position": "Senior Developer",
   "salary": 80000
};

// Creating an instance of the Employee class
var employee = new Employee(jsonData);

// Displaying the employee summary
employee.displayEmployeeSummary();

輸出

上述程式碼將產生以下輸出:

Name: John Smith
Position: Senior Developer
Salary: $80,000
Annual Bonus: $8,000

透過本教程,使用者學習瞭如何在TypeScript類內部轉換JSON物件。透過使用型別斷言,使用者可以確保型別安全並無縫地將JSON資料對映到結構化的TypeScript物件。此技術在處理基於JSON的API或處理需要在TypeScript專案中進行強型別的資料時非常有價值。

更新於:2023年8月31日

884 次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.