使用Partial <>的嵌套类序列化

时间:2018-11-29 16:23:48

标签: typescript

我想知道是否有一种(好的)方法可以通过json在Typescript中创建嵌套类?

我成功实现了这样的目标:

export class ImportEntity {
    public status: string;
    public Items: Item[];

   constructor(data: Partial<ImportEntity>) {
       Object.assign(this, data);
       this.mappingItems = [];

       if (data.Items)
           data.Items.forEach(item => { 
               this.Items.push(new Item(item));
           });
   }
}

export class Item {
    public column: string;
    public type: string;

    constructor(data: NestedPartial<MappingItem>) {
        Object.assign(this, data);
    }
}

但是手动处理嵌套类似乎很奇怪(从Java的角度来看:p)

谢谢。

1 个答案:

答案 0 :(得分:0)

也许您可以使用serializer.ts软件包? https://www.npmjs.com/package/serializer.ts

来自文档:

import {Type} from "serializer.ts/Decorators";


    export class Album {

        id: number;

        name: string;

        @Type(() => Photo)
        photos: Photo[];
    }

    export class Photo {
        id: number;
        filename: string;
    }

    let album = deserialize<Album>(Album, albumJson);
相关问题