简体   繁体   English

Angular2和Typescript-从嵌套JSON创建对象

[英]Angular2 & Typescript - Create object from nested JSON

I have a class which has multiple interfaces inside of it to model a JSON data. 我有一个具有多个接口的类,用于对JSON数据进行建模。 For example: 例如:

interface A {
   id: number;
}

interface B {
   name: string;
   surname?: string;
}

class MyClass implements A {
  people: B[];
  notes: string[];

  function1(){...}
  function2(){...}
}

And I have a JSON in the same structure: 我有一个相同结构的JSON:

{
  id: 1,
  people: [
    {
      name: "john"
    },
    {
      name: "alice",
      surname: "smith"
    }
  ],
  notes: [ "Very important top secret note" ]
}

Can I create an instance of MyClass from this JSON directly? 我可以直接从此JSON创建MyClass的实例吗?

Your data structure is almost the same as your class, you'd have to add an id property to the class 您的数据结构与您的类几乎相同,您必须在该类中添加一个id属性

class MyClass implements A {
    id: number;
    // ....
}

The problem is if you were trying to do something like this: 问题是,如果您尝试执行以下操作:

let data: MyClass = {
  id: 1,
  people: [
    {
      name: "john"
    },
    {
      name: "alice",
      surname: "smith"
    }
  ],
  notes: [ "Very important top secret note" ]
}

This won't work because your json does not have the methods (function1, function2). 这将不起作用,因为您的json没有方法(function1,function2)。

One solution would be to really instantiate the MyClass and pass the json, or have a constructor method for that like 一种解决方案是真正实例化MyClass并传递json,或者为此提供一个构造方法

class MyClass {
    static createFrom(jsonData: A & B): MyClass {
       // create the objct and return
    }
}

Or, you could create a variable of that type by combining an existing instance of the class and spreading the json. 或者,您可以通过组合该类的现有实例并传播json来创建该类型的变量。

Like so: 像这样:

let json = {
    id: 1,
    people: [
        {
            name: "john"
        },
        {
            name: "alice",
            surname: "smith"
        }
    ],
    notes: ["Very important top secret note"]
}
const c = new MyClass();

let mClass: MyClass = {...json, function1: c.function1, function2: c.function2 };

mClass.function1();

Link to playground 链接到游乐场

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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