Reputation: 53
I'm trying to stringify objects in Typescript that was implemented usign private properties like this
export class Foo {
private _property1:string;
private _property2:string;
private _property3:string;
get property1(): string {
return this._property1;
}
set property1(value: string) {
this._property1 = value;
}
get property2(): string {
return this._property2;
}
set property2(value: string) {
this._property2 = value;
}
get property3(): string {
return this._property3;
}
set property3(value: string) {
this._property3 = value;
}
}
But when i use JSON.stringfy(), the private properties are read and does'nt go through the get and set methods.
Expected:
{
"property1": "",
"property2": "",
"property3": "",
}
Received:
{
"_property1": "",
"_property2": "",
"_property3": "",
}
It is noticed that the property is underlined, but should not, Json should come with the name that was implemented in the getters and setters and not in private properties
Upvotes: 1
Views: 718
Reputation: 71901
JSON.stringify
only looks at object fields, not at methods or properties (getters/setters).
If
undefined
, a function, or a symbol is encountered during conversion it is either omitted (when it is found in an object)...
A getter or setter is defined as a function, and will therefore be ignored in the conversion. Only the private fields of the object will find their way in the JSON
. And they will only be there, if they are actually initialised.
Upvotes: 1