2017-02-23 117 views
0

在我Angular2-应用I'm接收通过HTTP请求的JSON响应那种看起来像:地图JSON响应到嵌套打字稿对象与rxjs

{ 
    "documents": [ 
    { 
     "title": "Example-Doc 1", 
     "versions": [ 
     { 
      "fileSize": 15360 
     }, 
     { 
      "fileSize": 2048 
     } 
     ] 
    }, 
    { 
     "title": "Example-Doc 2", 
     "versions": [ 
     { 
      "fileSize": 15360 
     }, 
     { 
      "fileSize": 2048 
     } 
     ] 
    } 
    ], 
    "meta": { 
    "total": [2] 
    } 
} 

现在我不知道如何映射这个结构到我的TypeScript类,我检查了不同的方法,但它从来没有工作。实际上我需要调用Version类的构造函数。

export class Document { 
    title: string;  // Titel des Dokuments 
    versions: Version[]; 
} 

回答

0

如果您要进行序列化和反序列化复杂的类需要,我建议你实现静态方法,你的类像fromJsontoJson - 但是不知道你的类答案的其余部分将是怎样的一个猜工作:

假设你有一个适当的fromJson,那么你可以像下面的地图数据:

const myDocuments: Document[] = myJson.documents.map(Document.fromJson); 

而且fromJson - 方法可以看看李关键字:

class Document { 
    constructor(public title: string, public versions: Version[]) 

    public static fromJson(json: any): Document { 
     return new Document(
      json.title, 
      json.versions.map(Version.fromJson) 
     ); 
    } 
} 

class Version { 
    constructor(public fileSize: number) {} 

    public static fromJson(json: any): Version { 
     return new Version(json.fileSize); 
    } 
}