javascript - 序列化 JS 对象以供离线使用

标签 javascript json serialization

在我的应用程序内部创建了一个复杂的对象(许多不同类型的属性..数组、函数、字符串等),它的创建是介于无法使用该部分的唯一因素应用程序离线。我的想法是缓存在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/

相关文章:

javascript - 为什么不能同时使用ajax和服务器发送事件?

javascript - 如何使用 JavaScript/JQuery 创建每 40 个字符自动换行

c# - ASP.NET Web API 本地主机 :xxxx/api/product defaults to Home Page and not JSON data(orXML)

java - jackson ,序列化引用的一个属性

json - 如何获取响应数据并将其解析为 JMeter 中的 HTTP header 管理器

java - 为什么 SAXException 是可序列化的?

javascript - RowFilter 不匹配时显示消息

jquery - 如何使用 GM_xmlhttpRequest 将序列化数组从客户端表单获取到服务器

c# - 将控件属性(例如 :TextBox. 文本)序列化/保存到自定义配置文件

javascript - "Rate this app"Ionic 应用程序中的 google play 商店链接