你如何将一个JSON对象转换为TypeScript类的实例,而不使用任何外部库?

huangapple go评论77阅读模式
英文:

How can I cast a JSON object to a TypeScript class instance without any external library?

问题

我正在尝试将一个JSON对象进行类型转换,示例如下:

class Person {
    constructor(
      public firstName, 
      public lastName
   ) {}

   function getName() {
      return this.firstName +   + this.lastName;
   }
}

目标是解析如下所示的JSON:

{
    firstName: “Max“,
    lastName: “Mustermann“
}

以便将其转换为上述类的实例,以访问所有属性和方法。

是否有一种简单的方法可以创建一个函数,使这种类型的JSON和类的转换功能成为可能?
同时,嵌套对象也应该是可能的。

我可以为每个不同的类编写一个工厂方法,但应该有一种更好的方法来获得这样的功能。

英文:

I am trying to cast a JSON object like the following example:

class Person {
    constructor(
      public firstName, 
      public lastName
   ) {}

   function getName() {
      return this.firstName + “ “ + this.lastName;
   }
}

The goal is to parse the JSON which looks like this:

    {
    firstName: “Max“,
    lastName: “Mustermann“
    }

to an instance of the above class to access all properties and methods.

Is there an easy way to create a function which can make such a functionality possible for such type of JSONs/classes?
Also nested objects should be possible.

I can write a factory method for every different class but there should be an better way to get such functionality.

答案1

得分: 1

创建你的类如下,注意构造函数:

class Person {
    public firstName: string;
    public lastName: string;

    public constructor(init?: Partial<Person>) {
        Object.assign(this, init);
    }

    function getName() {
        return this.firstName + " " + this.lastName;
    }
}

将 JSON 传递给这个构造函数:

let person = new Person({ firstName: "A", lastName: "B" });
console.log(person);
英文:

Use Object.assign

Create your class like this, observe the constructor

class Person {
       public firstName: string; 
       public lastName: string;

       public constructor(init?: Partial&lt;Person&gt;) {
        Object.assign(this, init);
       }

      function getName() {
        return this.firstName + “ “ + this.lastName;
      }
   }

Pass the json into this constructor

let person =  new Person({firstName: &quot;A&quot;, lastName: &quot;B&quot; });
console.log(person);

huangapple
  • 本文由 发表于 2023年5月29日 18:43:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/76356662.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定