+
81
-

js中序列化和反序列化对象的方法是什么?

js中序列化和反序列化对象的方法是什么?

高手回复

+
1
-
var a = {
"title": 'good', "name": "ddd", "age": 16
};
//序列化对象
console.log(JSON.stringify(a));
//反序列化对象
var newa = JSON.parse(JSON.stringify(a));

console.log(newa);

by ppzhuzhu
+
1
-
<script>
function serialize(obj, name) {
var result = "";
function serializeInternal(o, path) {
for (p in o) {
var value = o[p];
if (typeof value != "object") {
if (typeof value == "string") {
result += "\n" + path + "[" + (isNaN(p)?"\""+p+"\"": p) + "] = " + "\"" + value.replace(/\"/g, "\\\"") + "\""+";";
} else {
result += "\n" + path + "[" + (isNaN(p)?"\""+p+"\"": p) + "] = " + value+";";
}
} else {
if (value instanceof Array) {
result += "\n" + path +"[" + (isNaN(p)?"\""+p+"\"": p) + "]"+"="+"new Array();";
serializeInternal(value, path + "[" + (isNaN(p)?"\""+p+"\"": p) + "]");
} else {
result += "\n" + path + "[" + (isNaN(p)?"\""+p+"\"": p) + "]"+"="+"new Object();";
serializeInternal(value, path +"[" + (isNaN(p)?"\""+p+"\"": p) + "]");
}
}
}
}
serializeInternal(obj, name);
return result;
}


function A() {
this.name = "A";
this.arr = new Array();
this.put = function(para) {
this.arr[this.arr.length] = para;
}
}
function B() {
this.name = "B";
this.show = "";
}

var a = new A();

var b = new B();
b.show = function() {
alert("function 1");
}

var b2 = new B();
b2.show = function() {
alert("function 2");
}

a.put(b);
a.put(b2);
//序列化
console.log(serialize(a, "a"));
//反序列化
var deserialization_lang = serialize(a, "a"); //deserialization_lang生成的语句
var a = new Object();
eval(deserialization_lang);
a.arr[0].show(); //成功的弹出function 1
</script>

by ppzhuzhu
我知道答案,我要回答