我遇到了一个不知道如何处理的类序列化问题。
我从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值。这中断了应用程序其他部分的反序列化。
序列化接口给了我想要的东西,但我还没有找到从类到接口表示的直接方法。这个问题变得更加困难,因为我在层次结构中反序列化数据(请参阅构造函数中的模块映射(。
你通常如何解决这个问题?
据我所见,您并没有真正实现ILockerModel
。这不应该引发错误吗?
当我运行它时,我会得到以下信息:
类型"LockerModel"缺少类型"ILockerModel"中的以下属性:id、lockerId、ownerId、模块
另一件事是JSON.strigify()
只是获取对象并对其所有属性进行字符串表示。它不在乎你的收获者。如果你想让它转换成正确的格式,你应该给它一个正确格式的对象。
一种解决方案是通过使用map
和reduce
:的组合,从所有密钥中删除"_">
const input = {
_test: 123,
_hello: 'world'
};
console.log(input);
console.log(JSON.stringify(input));
const convertToJson = (obj) => {
return Object.entries(obj) // Create array from object
.map(([key, value]) => [ // change key to remove '_'
key.startsWith('_') ? key.substring(1) : key,
value
])
.reduce((acc, [key, value]) => { // Transform back to object
acc[key] = value;
return acc;
}, {});
}
const output = convertToJson(input);
console.log(output);
console.log(JSON.stringify(output));
或者,如果您被允许使用ES10:
const input = {
_test: 123,
_hello: 'world'
};
console.log(input);
console.log(JSON.stringify(input));
const convertToJson = (obj) => {
return Object.fromEntries( // Create Object from array
Object.entries(obj) // Create array from object
.map(([key, value]) => [ // change key to remove '_'
key.startsWith('_') ? key.substring(1) : key,
value
])
);
}
const output = convertToJson(input);
console.log(output);
console.log(JSON.stringify(output));