简体   繁体   English

将JSON转换为TypeScript对象的最佳方法是什么?

[英]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 这些是我的问题

  1. Is this a perfect solution ? 这是一个完美的解决方案吗?
  2. Is there any better solution than this ? 有没有比这更好的解决方案了?
  3. Is there any built-in solution for this in 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM