在JavaScript中序列化/反序列化对象的最佳方法? [英] Best way to serialize/unserialize objects in 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小提琴。
我的问题是:是否有最佳实践/模式/提示来恢复同类型的对象在序列化之前(在这种情况下是类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
实例的特殊data属性中。例如:
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)
.
这样可以保持 toJson
和 fromJson
方法简单但你必须调整你的其他功能。
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屋!