Angular 的 Json.stringify 有 属性 个问题

Angular's Json.stringify with property problems

我正在尝试将 Typescript 中的对象字符串化,这些对象是使用这样的私有属性实现的

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;
   }


}

但是当我使用 JSON.stringfy() 时,私有属性被读取并且不通过 get 和 set 方法。

预计:

{
  "property1": "",
  "property2": "",
  "property3": "",

}

收到:

{
  "_property1": "",
  "_property2": "",
  "_property3": "",

}

注意到 属性 有下划线,但不应该,Json 应该带有在 getter 和 setter 中实现的名称,而不是在私有属性中实现的名称

JSON.stringify 只查看对象字段,不查看方法或属性 (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 或 setter 被定义为函数,因此在转换中将被忽略。只有对象的私有字段才能在 JSON 中找到它们的位置。而且它们只会在那里,如果它们实际上被初始化了。