我想知道是否有一种(好的)方法可以通过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)
谢谢。
答案 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);