How To Use Json To Create Object That Inherits From Object Type?
I know how to use JSON to create objects, but there doesn't seem to be away to use JSON to create an object that is of a specific object type. Here's an example of an Object and cr
Solution 1:
I don't imagine so. I'd create a function on the Person class to initialise from a JSON object if I were you.
functionPerson() {
this.loadFromJSON = function(json) {
this.FirstName = json.FirstName;
};
}
If you didn't know what class the JSON object was representing beforehand, perhaps add an extra variable into your JSON.
{ _className : "Person", FirstName : "Mike" }
And then have a 'builder' function which interprets it.
functionbuildFromJSON(json) {
var myObj = new json["_className"]();
myObj.loadFromJSON(json);
return myObj;
}
Update: since you say the class is part of a third-party library which you can't change, you could either extend the class with prototyping, or write a function which just populates the class externally.
eg:
Person.prototype.loadFromJSON = function(json) {
// as above...
};
or
functionpopulateObject(obj, json) {
for (var i in json) {
// you might want to put in a check here to test// that obj actually has an attribute named i
obj[i] = json[i];
}
}
Solution 2:
You could allow new Person() to accept an object to populate attributes with as a parameter.
var you = new Person({ firstName: 'Mike' });
Solution 3:
You can derive an object from theirs. Your constructor can accept the object you want, but call their constructor in an unaffected fashion:
functionyourWrapper(obj) {
theirObject.call(this);
for (var s in obj) {
this[s] = obj[s];
}
}
yourWrapper.prototype = newtheirObject();
Or something like that :)
Post a Comment for "How To Use Json To Create Object That Inherits From Object Type?"