[英]What is the best way to convert JSON to TypeScript Object?
I've JSON
string 我有
JSON
字符串
const json = '{ "first_name": "John", "last_name": "Doe"}';
and a class User
和一个班级
User
class User {
constructor(
public first_name: string,
public last_name: string
) {
}
public getFullName = (): string => {
return this.first_name + ' ' + this.last_name;
};
}
and when I try this 当我尝试这个
const user: User = JSON.parse(json);
console.log(user.first_name); // Works, prints "John"
console.log(user.last_name); // Works, prints "Doe"
console.log(user.getFullName()); //Error: TypeError: user.getFullName is not a function
I know the error happened, because JSON.parse
simply matched the User
type but not methods in it. 我知道发生了错误,因为
JSON.parse
仅匹配User
类型,但不匹配其中的方法。
So to fix this, I wrote a fromJSON
static method in User
class to parse manually, 因此,为了解决此问题,我在
User
类中编写了fromJSON
静态方法来进行手动解析,
public static fromJSON = (json: string): User => {
const jsonObject = JSON.parse(json);
return new User(
jsonObject.first_name,
jsonObject.last_name
);
};
So these are my questions 这些是我的问题
TypeScript
? TypeScript
对此有任何内置的解决方案吗? It's a decent solution. 这是一个不错的解决方案。 A better one would be to use
Object.assign
so as to not have to write all the assignments as this ca get out of hand if there are many properties, but either will work fine. 更好的方法是使用
Object.assign
这样就不必编写所有分配,因为如果有很多属性,这种分配会失去控制,但是两者都可以正常工作。
class User {
public first_name!: string;
public last_name!: string;
constructor(data: Partial<User>) {
Object.assign(this, data);
}
public getFullName (): string {
return this.first_name + ' ' + this.last_name;
};
public static fromJSON = (json: string): User => {
const jsonObject = JSON.parse(json);
return new User(jsonObject);
};
}
There is no buil-in solution for this in typescript, Object.assign
is the closest to it. 在打字稿中没有内置解决方案,
Object.assign
是最接近的。 You might consider changing the constructor dynamically as detailed here , that will convert the object to an instance of the class but will not necessarily perform better. 您可以考虑按此处详细说明动态更改构造函数,这会将对象转换为类的实例,但不一定会表现更好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.