在 JavaScript 中序列化/反序列化对象的最佳方法? [英] Best way to serialize/unserialize objects in JavaScript?

查看:27
本文介绍了在 JavaScript 中序列化/反序列化对象的最佳方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序中有许多 JavaScript 对象,例如:

I have many JavaScript objects in my application, something like:

function Person(age) {
    this.age = age;
    this.isOld = function (){
        return this.age > 60;
    }
}
// before serialize, ok
var p1 = new Person(77);
alert("Is old: " + p1.isOld());

// after, got error Object #<Object> has no method 'isOld'
var serialize = JSON.stringify(p1);
var _p1 = JSON.parse(serialize);
alert("Is old: " + _p1.isOld());

参见 JS Fiddle.

我的问题是:是否有最佳实践/模式/技巧可以恢复序列化之前相同类型的对象(在本例中是类 Person 的实例)?

My question is: is there a best practice/pattern/tip to recover my object in same type it was before serialization (instances of class Person, in this case)?

我的要求:

  • 优化磁盘使用:我在内存中有一个很大的对象树.所以,我不想存储函数.
  • 解决方案可以使用 jQuery 和另一个库来序列化/反序列化.

推荐答案

JSON 没有作为数据类型的函数.您只能序列化字符串、数字、对象、数组和布尔值(和 null)

JSON has no functions as data types. You can only serialize strings, numbers, objects, arrays, and booleans (and null)

您可以创建自己的 toJson 方法,只传递真正需要序列化的数据:

You could create your own toJson method, only passing the data that really has to be serialized:

Person.prototype.toJson = function() {
    return JSON.stringify({age: this.age});
};

类似反序列化:

Person.fromJson = function(json) {
    var data = JSON.parse(json); // Parsing the json string.
    return new Person(data.age);
};

用法是:

var serialize = p1.toJson();
var _p1 = Person.fromJson(serialize);
alert("Is old: " + _p1.isOld());

<小时>

为了减少工作量,您可以考虑将所有需要序列化的数据存储在每个 Person 实例的特殊数据"属性中.例如:


To reduce the amount of work, you could consider to store all the data that needs to be serialized in a special "data" property for each Person instance. For example:

function Person(age) {
    this.data = {
        age: age
    };
    this.isOld = function (){
        return this.data.age > 60 ? true : false;
    }
}

然后序列化和反序列化只是调用 JSON.stringify(this.data) 并且设置实例的数据将是 instance.data = JSON.parse(json).

then serializing and deserializing is merely calling JSON.stringify(this.data) and setting the data of an instance would be instance.data = JSON.parse(json).

这将使 toJsonfromJson 方法保持简单,但您必须调整其他函数.

This would keep the toJson and fromJson methods simple but you'd have to adjust your other functions.

附注:

您应该将 isOld 方法添加到函数的原型中:

You should add the isOld method to the prototype of the function:

Person.prototype.isOld = function() {}

否则,每个实例都有自己的函数实例,这也会增加内存.

Otherwise, every instance has it's own instance of that function which also increases memory.

这篇关于在 JavaScript 中序列化/反序列化对象的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆