【问题标题】:Angular's Json.stringify with property problemsAngular 的 Json.stringify 有属性问题
【发布时间】:2017-11-07 12:23:21
【问题描述】:

我正在尝试对 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

标签: json angular typescript getter-setter stringify


【解决方案1】:

JSON.stringify 只查看对象字段,而不查看方法或属性(getter/setter)。

如果在转换过程中遇到undefined、函数或符号,则将其省略(当在对象中找到时)

...

getter 或 setter 被定义为函数,因此在转换中将被忽略。只有对象的私有字段才能在JSON 中找到它们的方式。并且它们只有在实际初始化时才会存在。

【讨论】:

    猜你喜欢
    • 2022-01-20
    • 2015-09-22
    • 1970-01-01
    • 1970-01-01
    • 2019-05-25
    • 1970-01-01
    • 2013-11-15
    • 2018-04-11
    • 1970-01-01
    相关资源
    最近更新 更多