【发布时间】:2020-12-14 04:13:40
【问题描述】:
我遇到了一个我不知道如何处理的类的序列化问题。
我从 REST 或数据库请求创建对象,如下所示:
export interface ILockerModel {
id: string
lockerId: string
ownerId: string
modules: IModuleModel[]
}
export class LockerModel implements ILockerModel {
private _id: string
private _lockerId: string
private _ownerId: string
private _modules: ModuleModel[]
constructor(document: ILockerModel) {
this._id = document.id
this._lockerId = document.lockerId
this._ownerId = document.ownerId
this._modules = document.modules.map(m => new ModuleModel(m))
}
// Utility methods
}
然后,我有多种实用方法,可以更轻松地使用模型、在列表中添加和删除内容等等。
完成后,我想将对象保存到文档数据库或在 REST 响应中返回,因此我调用 JSON.stringify(objectInstance)。但是,这给了我这个类,但所有属性都加了下划线 (_),而不是我的 getter 值。这会破坏我应用程序其他部分的反序列化。
序列化接口给了我我想要的东西,但我还没有找到从类到接口表示的直接方法。问题变得更加棘手,因为我在层次结构中反序列化数据(请参阅构造函数中的模块映射)。
你通常如何解决这个问题?
【问题讨论】:
-
这里是一个使用 get/set 进行序列化的例子:stackoverflow.com/a/44315652/1762224
标签: javascript json typescript getter