JSON.stringify仅序列化TypeScript获取器 [英] JSON.stringify serialize only TypeScript getters

查看:114
本文介绍了JSON.stringify仅序列化TypeScript获取器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的班级结构如下...

I have the following class structure...

export abstract class PersonBase {
    public toJSON(): string {
        let obj = Object.assign(this);
        let keys = Object.keys(this.constructor.prototype);
        obj.toJSON = undefined;
        return JSON.stringify(obj, keys);
    }
}

export class Person extends PersonBase {

    private readonly _firstName: string;
    private readonly _lastName: string;

    public constructor(firstName: string, lastName: string) {
        this._firstName = firstName;
        this._lastName = lastName;
    }

    public get first_name(): string {
        return this._firstName;
    }

    public get last_name(): string {
        return this._lastName;
    }
}

export class DetailPerson extends Person {

    private _address: string;

    public constructor(firstName: string, lastName: string) {
        super(firstName, lastName);
    }

    public get address(): string {
        return this._address;
    }

    public set address(addy: string) {
        this._address = addy;
    }
}

我试图获取toJSON()以输出整个对象层次结构中的所有getter(私有属性除外)...

I am trying to get toJSON() to output all the getters (excluding the private properties) from the full object hierarchy...

因此,如果我有一个DetailPerson实例并调用.toJSON(),我想查看以下输出...

So if i have a DetailPerson instance and i call .toJSON() i want to see the following output...

{ "address":某些地址", "first_name":我的名字", "last_name":我的姓氏" }

{ "address": "Some Address", "first_name": "My first name", "last_name": "My last name" }

我使用了本文中的一种解决方案,但是并不能解决我的特殊用例……我并没有在输出中得到所有的吸气剂.

I used one of the solutions from this article but it doesn't solve my particular use case... I am not getting all the getters in the output.

结合使用JSON.stringify和TypeScript getter/setter

为了获得所需的结果,我需要在此处进行哪些更改?

What do i need to change here to get the result i am looking for?

推荐答案

您提供的链接使用Object.keys,在原型上保留了属性.

The link you provided uses Object.keys which leaves out properties on the prototype.

您可以使用for...in代替Object.keys:

public toJSON(): string {
    let obj: any = {};

    for (let key in this) {
        if (key[0] !== '_') {
            obj[key] = this[key];
        }
    }

    return JSON.stringify(obj);
}

这是我的尝试,以递归方式仅返回getter,而不假定非getter以下划线开头.我确定我错过了一些陷阱(循环引用,某些类型的问题),但这是一个不错的开始:

This is my attempt to return only getters, recursively, without assuming that non-getters start with underscores. I'm sure there are gotchas I missed (circular references, issues with certain types), but it's a good start:

abstract class PersonBase {
  public toJSON(): string {
    return JSON.stringify(this._onlyGetters(this));
  }

  private _onlyGetters(obj: any): any {
    // Gotchas: types for which typeof returns "object"
    if (obj === null || obj instanceof Array || obj instanceof Date) {
      return obj;
    }

    let onlyGetters: any = {};

    // Iterate over each property for this object and its prototypes. We'll get each
    // property only once regardless of how many times it exists on parent prototypes.
    for (let key in obj) {
      let proto = obj;

      // Check getOwnPropertyDescriptor to see if the property is a getter. It will only
      // return the descriptor for properties on this object (not prototypes), so we have
      // to walk the prototype chain.
      while (proto) {
        let descriptor = Object.getOwnPropertyDescriptor(proto, key);

        if (descriptor && descriptor.get) {
          // Access the getter on the original object (not proto), because while the getter
          // may be defined on proto, we want the property it gets to be the one from the
          // lowest level
          let val = obj[key];

          if (typeof val === 'object') {
            onlyGetters[key] = this._onlyGetters(val);
          } else {
            onlyGetters[key] = val;
          }

          proto = null;
        } else {
          proto = Object.getPrototypeOf(proto);
        }
      }
    }

    return onlyGetters;
  }
}

这篇关于JSON.stringify仅序列化TypeScript获取器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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