如何在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.