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

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

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

问题

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

  1. class Person {
  2. constructor(
  3. public firstName,
  4. public lastName
  5. ) {}
  6. function getName() {
  7. return this.firstName + + this.lastName;
  8. }
  9. }

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

  1. {
  2. firstName: Max“,
  3. lastName: Mustermann
  4. }

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

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

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

英文:

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

  1. class Person {
  2. constructor(
  3. public firstName,
  4. public lastName
  5. ) {}
  6. function getName() {
  7. return this.firstName + + this.lastName;
  8. }
  9. }

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

  1. {
  2. firstName: Max“,
  3. lastName: Mustermann
  4. }

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

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

  1. class Person {
  2. public firstName: string;
  3. public lastName: string;
  4. public constructor(init?: Partial<Person>) {
  5. Object.assign(this, init);
  6. }
  7. function getName() {
  8. return this.firstName + " " + this.lastName;
  9. }
  10. }

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

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

Use Object.assign

Create your class like this, observe the constructor

  1. class Person {
  2. public firstName: string;
  3. public lastName: string;
  4. public constructor(init?: Partial&lt;Person&gt;) {
  5. Object.assign(this, init);
  6. }
  7. function getName() {
  8. return this.firstName + + this.lastName;
  9. }
  10. }

Pass the json into this constructor

  1. let person = new Person({firstName: &quot;A&quot;, lastName: &quot;B&quot; });
  2. 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:

确定