当JSON数据具有嵌套对象时,我无法将JSON转换为Javascript对象。顶级'人物'对象得到了很好的重建,但是' Residence'对象属性不是
function Person(first, last) {
this.FirstName = first;
this.LastName = last;
this.Residence = {};
}
Person.Revive = function (data) {
return new Person(data.FirstName, data.LastName);
}
Object.defineProperty(Person.prototype, "FullName", {
get: function() { return this.FirstName + " " + this.LastName; }
});
Person.prototype.toJSON = function () {
this.__class__ = "Person";
return this;
});
function Residence(lat, long) {
this.Latitude = lat;
this.Longitude = long;
}
Residence.prototype.toJSON = function () {
this.__class__ = "Residence";
return this;
}
Residence.Revive = function (data) {
return new Residence(data.Latitude, data.Longitude);
}
Object.defineProperty(Residence.prototype, "Location", {
get: function () { return this.Latitude + ", " + this.Longitude; }
});
var p = new Person("Foo", "Bar");
p.Residence = new Residence(44, 33);
console.log("Full name = " + p.FullName);
console.log("Location = " + p.Residence.Location);
var serialization = JSON.stringify(p);
console.log(serialization);
var rawObj = JSON.parse(serialization, function (key, value) {
if (value instanceof Object && value.__class__ == 'Person') {
return Person.Revive(value);
}
if (value instanceof Object && value.__class__ == 'Residence') {
return Residence.Revive(value);
}
return value;
});
console.log("Full name = " + rawObj.FullName);
console.log("Location = " + rawObj.Residence.Location);
JSON.parse函数确实为' Residence'提供了一个键/值对。对象,并创建并返回一个新的Residence对象。然而,由此产生的< rawObj.Residence'只是一个空对象。谁能指出我做错了什么?
控制台输出如下:
Full name = Foo Bar
Location = 44, 33
{"FirstName":"Foo","LastName":"Bar","Age":22,"Residence":{"Latitude":44,"Longitude":33,"__class__":"Residence"},"__class__":"Person"}
Full name = Foo Bar
Location = undefined
答案 0 :(得分:2)
var p = new Person("Foo", "Bar"); p.Residence = new Residence(44, 33);
好吧,如果你正在构建这样的Person
个对象,你也必须像这样重振它们:
Person.Revive = function (data) {
var p = new Person(data.FirstName, data.LastName);
p.Residence = data.Residence;
return p;
};
当然,首先将住所作为Person
的{可选?)参数可能是个好主意。