javascript - JSON.parse(), reconnecting to nested objects -
i'm having trouble converting json javascript objects when json data has nested objects. top level 'person' object gets recreated fine, 'residence' object property not
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);
the json.parse function key/value pair 'residence' object, , new residence object created , returned. however, resulting 'rawobj.residence' empty object. can point out i'm doing wrong?
the console output follows:
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
var p = new person("foo", "bar"); p.residence = new residence(44, 33);
well, if constructing person
objects that, you'll have revive them well:
person.revive = function (data) { var p = new person(data.firstname, data.lastname); p.residence = data.residence; return p; };
of course, might idea make residence (optional?) parameter person
in first place.
Comments
Post a Comment