Angular's Json.stringify with property problems

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-24 10:02:40

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/44390783/angulars-json-stringify-with-property-problems

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!