【问题标题】:Serialize a JS object for offline use序列化一个 JS 对象以供离线使用
【发布时间】:2017-05-09 21:25:43
【问题描述】:

在我的应用程序内部创建了一个复杂的对象(许多不同类型的属性..数组、函数、字符串等),它的创建是唯一介于使用和无法使用该部分的应用离线。我的想法是缓存在localStorage中,然后离线恢复。

我尝试了明显的候选对象 JSON.stringify() 和 .toString(),它们都没有产生所需的序列化。也许我的整个方法有缺陷。

任何想法如何做到这一点?

【问题讨论】:

标签: javascript json serialization


【解决方案1】:

你不能序列化函数,你最好创建一个可以序列化和反序列化的类。这是一个例子:

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);

【讨论】:

  • 所以基本上我只会存储从头开始创建对象所需的数据?似乎是个好主意。
  • 是的,完全正确。您仅序列化数据并从 localStorage 重新填充对象的实例(使用您的所有方法)
猜你喜欢
  • 2021-09-25
  • 2018-03-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多