如何在 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 类,其属性为 name、age 和 email。构造函数接受一个 any 类型的参数 json,表示 JSON 对象。
之后,我们使用类型断言将 JSON 对象强制转换为 Person 类的实例。然后将 castedJson 对象的属性赋值给该类的相应属性。
接下来,我们在 Person 类中定义一个名为 displayDetails() 的方法。此方法通过将人员登录到控制台来显示其姓名、年龄和电子邮件地址。
最后,我们创建一个名为 jsonData 的 JSON 对象,用于表示人员的详细信息。我们将 jsonData 传递给构造函数,创建一个名为 person 的 Person 类实例。然后,我们调用 person 对象的 displayDetails() 方法来访问和显示人员的详细信息。
// 定义 Person 类
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}`);
}
}
// 创建一个代表 Person 的 JSON 对象
const jsonData = {
"name": "John Doe",
"age": 30,
"email": "johndoe@example.com"
};
// 创建 Person 类的实例
const person = new Person(jsonData);
// 访问并显示 Person 的详细信息
person.displayDetails();
编译后,它会生成以下 JavaScript 代码 -
// 定义 Person 类
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;
}());
// 创建一个代表 Person 的 JSON 对象
var jsonData = {
"name": "John Doe",
"age": 30,
"email": "johndoe@example.com"
};
// 创建 Person 类的实例
var person = new Person(jsonData);
// 访问并显示 Person 的详细信息
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()}`);
}
}
// 创建一个代表员工的 JSON 对象
const jsonData = {
"name": "John Smith",
"position": "Senior Developer",
"salary": 80000
};
// 创建 Employee 类的实例
const employee = new Employee(jsonData);
// 显示员工概要
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;
}());
// 创建一个代表员工的 JSON 对象
var jsonData = {
"name": "John Smith",
"position": "Senior Developer",
"salary": 80000
};
// 创建 Employee 类的实例
var employee = new Employee(jsonData);
// 显示员工概要
employee.displayEmployeeSummary();
输出
上述代码将产生以下输出 -
Name: John Smith Position: Senior Developer Salary: $80,000 Annual Bonus: $8,000
通过本教程,用户学习了如何在 TypeScript 类中转换 JSON 对象。通过使用类型断言,用户可以确保类型安全,并将 JSON 数据无缝映射到结构化的 TypeScript 对象。在处理基于 JSON 的 API 或在 TypeScript 项目中处理需要强类型的数据时,此技术非常有用。

