如何将 JSON 对象解析为 TypeScript 对象 [英] How to parse a JSON object to a TypeScript Object
问题描述
我目前正在尝试将我收到的 JSON 对象转换为具有相同属性的 TypeScript 类,但我无法让它工作.我做错了什么?
I am currently trying to convert my received JSON Object into a TypeScript class with the same attributes and I cannot get it to work. What am I doing wrong?
员工类
export class Employee{
firstname: string;
lastname: string;
birthdate: Date;
maxWorkHours: number;
department: string;
permissions: string;
typeOfEmployee: string;
note: string;
lastUpdate: Date;
}
员工字符串
{
"department": "<anystring>",
"typeOfEmployee": "<anystring>",
"firstname": "<anystring>",
"lastname": "<anystring>",
"birthdate": "<anydate>",
"maxWorkHours": <anynumber>,
"username": "<anystring>",
"permissions": "<anystring>",
"lastUpdate": "<anydate>"
//I will add note later
}
我的尝试
let e: Employee = new Employee();
Object.assign(e, {
"department": "<anystring>",
"typeOfEmployee": "<anystring>",
"firstname": "<anystring>",
"lastname": "<anystring>",
"birthdate": "<anydate>",
"maxWorkHours": 3,
"username": "<anystring>",
"permissions": "<anystring>",
"lastUpdate": "<anydate>"
});
console.log(e);
推荐答案
编译器允许您将 JSON.parse
返回的对象转换为类的原因是因为 typescript 基于结构子类型.
您实际上并没有 Employee
的实例,而是有一个具有相同属性的对象(如您在控制台中看到的那样).
The reason that the compiler lets you cast the object returned from JSON.parse
to a class is because typescript is based on structural subtyping.
You don't really have an instance of an Employee
, you have an object (as you see in the console) which has the same properties.
一个更简单的例子:
class A {
constructor(public str: string, public num: number) {}
}
function logA(a: A) {
console.log(`A instance with str: "${ a.str }" and num: ${ a.num }`);
}
let a1 = { str: "string", num: 0, boo: true };
let a2 = new A("stirng", 0);
logA(a1); // no errors
logA(a2);
(操场上的代码)
没有错误,因为a1
满足A
类型,因为它拥有它的所有属性,而且logA
函数可以在没有运行时调用错误即使它收到的不是 A
的实例,只要它具有相同的属性.
There's no error because a1
satisfies type A
because it has all of its properties, and the logA
function can be called with no runtime errors even if what it receives isn't an instance of A
as long as it has the same properties.
当你的类是简单的数据对象并且没有方法时,这很有效,但是一旦你引入了方法,事情就会变得很糟糕:
That works great when your classes are simple data objects and have no methods, but once you introduce methods then things tend to break:
class A {
constructor(public str: string, public num: number) { }
multiplyBy(x: number): number {
return this.num * x;
}
}
// this won't compile:
let a1 = { str: "string", num: 0, boo: true } as A; // Error: Type '{ str: string; num: number; boo: boolean; }' cannot be converted to type 'A'
// but this will:
let a2 = { str: "string", num: 0 } as A;
// and then you get a runtime error:
a2.multiplyBy(4); // Error: Uncaught TypeError: a2.multiplyBy is not a function
(代码在操场上)
这很好用:
const employeeString = '{"department":"<anystring>","typeOfEmployee":"<anystring>","firstname":"<anystring>","lastname":"<anystring>","birthdate":"<anydate>","maxWorkHours":0,"username":"<anystring>","permissions":"<anystring>","lastUpdate":"<anydate>"}';
let employee1 = JSON.parse(employeeString);
console.log(employee1);
(操场上的代码)
如果您尝试在对象不是字符串时对它使用 JSON.parse
:
If you're trying to use JSON.parse
on your object when it's not a string:
let e = {
"department": "<anystring>",
"typeOfEmployee": "<anystring>",
"firstname": "<anystring>",
"lastname": "<anystring>",
"birthdate": "<anydate>",
"maxWorkHours": 3,
"username": "<anystring>",
"permissions": "<anystring>",
"lastUpdate": "<anydate>"
}
let employee2 = JSON.parse(e);
然后你会得到错误,因为它不是一个字符串,它是一个对象,如果你已经有了这种形式的它,那么就没有必要使用 JSON.parse
.
Then you'll get the error because it's not a string, it's an object, and if you already have it in this form then there's no need to use JSON.parse
.
但是,正如我所写的,如果你采用这种方式,那么你将没有类的实例,只有一个与类成员具有相同属性的对象.
But, as I wrote, if you're going with this way then you won't have an instance of the class, just an object that has the same properties as the class members.
如果你想要一个实例,那么:
If you want an instance then:
let e = new Employee();
Object.assign(e, {
"department": "<anystring>",
"typeOfEmployee": "<anystring>",
"firstname": "<anystring>",
"lastname": "<anystring>",
"birthdate": "<anydate>",
"maxWorkHours": 3,
"username": "<anystring>",
"permissions": "<anystring>",
"lastUpdate": "<anydate>"
});
这篇关于如何将 JSON 对象解析为 TypeScript 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!