javascript - Is this the best pattern for creating objects that have been JSON serialized? -
i'm working on project have nice set of objects serialize , send down wire when user calls rest api. problem json.stringify()
, json.parse()
not support methods, private data , properties defined object.defineproperty/defineproperties
; publicly visible fields [de]serialized.
i haven't come across many examples of consumer of javascript api deserializing response payload pojo members, properties, etc. simple pattern i've come isn't interesting , i'm wondering if there more common or superior patterns accomplishing same thing?
consider example:
var mytype = function(name, age) { this._name = name; this._age = age; } // add properties object.defineproperties(mytype.prototype, { 'name': { get: function() {return this._name;} }, 'age': { get: function() {return this._age;} } }); // add method mytype.prototype.tostring = function() { return this._name + ' ' + this._age; } // add 'static' deserialize method mytype.fromjson = function(serializedme) { var tmp = json.parse(serializedme); return new mytype(tmp._name, tmp._age); } var = new mytype('steve', 38); console.log('i ' + i.name + ' , age ' + i.age); // simulate serialization var payloadtosend = json.stringify(i); // send client... // client wants work full-fledged mytype instance... var clientinstanceofmytype = mytype.fromjson( payloadtosend ); console.log(clientinstanceofmytype.tostring());
is best can do? suppose comes down best creation pattern creating object methods , properties json.
Comments
Post a Comment