在我的应用程序内部创建了一个复杂的对象(许多不同类型的属性..数组、函数、字符串等),它的创建是介于无法使用该部分的唯一因素应用程序离线。我的想法是缓存在localStorage中,然后离线模式恢复。
我尝试了明显的候选者,JSON.stringify() 和 .toString(),它们都没有产生所需的序列化。也许我的整个方法是有缺陷的。
有什么想法可以做到这一点吗?
最佳答案
您无法序列化函数,最好创建一个可以序列化和反序列化的类。这是一个例子:
class Example {
constructor(data) {
this.data = data;
}
setKey(key, value) {
this.data[key] = value;
return this;
}
getKey(key) {
return this.data[key];
}
serialize() {
return JSON.stringify(this.data);
}
}
const example = new Example({ foo: 'bar' });
example.setKey('fizz', 'buzz');
// save item in local storage
localStorage.setItem('example', example.serialize());
// see the stringified version
console.log('serialized', localStorage.getItem('example'));
// get the json out
const json = localStorage.getItem('example');
// create an instance of Example using the parsed json
const example2 = new Example(JSON.parse(json));
// use rehydrated instance
console.log(example2.getKey('fizz'));
如果您不想定义 serialize()
方法,请注意:如果您向类添加 toJSON()
方法,您可以指定您想要的方法待连载:
toJSON() {
return this.data;
}
当您调用 JSON.stringify(exampleInstance)
时,它将触发 toJSON()
方法,并且只会序列化 toJSON()
返回的内容.
如果您希望在从 localStorage 获取数据后跳过 JSON.parse
步骤,则可以提供一个静态方法来为您提供填充的实例:
class Example {
// insert rest of the class above here
static fromLocalStorage(json) {
return new this(JSON.parse(json));
}
}
// same code as before
const json = localStorage.getItem('example');
const example2 = Example.fromLocalStorage(json);
关于javascript - 序列化 JS 对象以供离线使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43880119/