Angular的Json.stringify存在属性问题 [英] Angular's Json.stringify with property problems

查看:198
本文介绍了Angular的Json.stringify存在属性问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对Typescript中的对象进行字符串化,该对象是通过像这样的私有属性实现的

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


}

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

But when i use JSON.stringfy(), the private properties are read and does'nt go through the get and set methods.

预期:

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

}

已收到:

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

}

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

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

推荐答案

JSON.stringify only looks at object fields, not at methods or properties (getters/setters).

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

If undefined, a function, or a symbol is encountered during conversion it is either omitted (when it is found in an object)

...

getter或setter被定义为一个函数,因此在转换中将被忽略.在JSON中,只有对象的私有字段会找到它们的方式.而且只有在实际初始化的情况下,它们才会在那里.

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.

这篇关于Angular的Json.stringify存在属性问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆