Christian Droulers Christian Droulers - 4 months ago 9
Javascript Question

Object.defineProperty on a prototype prevents JSON.stringify from serializing it

I'm using TypeScript to define some classes and when I create a property, it generates the equivalent to

Class1
in the following plunkr:

http://plnkr.co/edit/NXUo7zjJZaUuyv54TD9i?p=preview

var Class1 = function () {
this._name = "test1";
}

Object.defineProperty(Class1.prototype, "Name", {
get: function() { return this._name; },
set: function(value) { this._name = value; },
enumerable: true
});

JSON.stringify(new Class1()); // Will be "{"_name":"test1"}"


When serializing, it doesn't output the property I just defined.

instance2
and
instance3
behave as I'd expect by serializing the defined property. (see the plunkr output).

My actual question is: Is this normal?

If so, how do I work around it in the most efficient way?

Answer

You can define a toJSON() method on your prototype to customize how instances are serialized.

Class1.prototype.toJSON = function () {
    return {
        Name: this.Name
    };
};
JSON.stringify(new Class1()); // Will be '{"Name":"test1"}'