Using JSON.stringify in conjunction with TypeScript getter/setter

大城市里の小女人 提交于 2019-11-28 03:11:17

问题


I am using getter/setter accessors in TypeScript. As it is not possible to have the same name for a variable and method, I started to prefix the variable with a lower dash, as is done in many examples:

private _major: number;

get major(): number {
  return this._major;
}
set major(major: number) {
  this._major = major;
}

Now when I use the JSON.stringify() method to convert the object into a JSON string, it will use the variable name as the key: _major.

As I don't want the JSON file to have all keys prefixed with a lower dash, is there any possibility to make TypeScript use the name of the getter method, if available? Or are there any other ways to use the getter/setter methods but still produce a clean JSON output?

I know that there are ways to manually modify the JSON keys before they are written to the string output. I am curious if there is simpler solution though.

Here is a JSFiddle which demonstrates the current behaviour.


回答1:


No, you can't have JSON.stringify using the getter/setter name instead of the property name.

But you can do something like this:

class Version {
    private _major: number;

    get major(): number {
        return this._major;
    }

    set major(major: number) {
        this._major = major;
    }

    toJsonString(): string {
        let json = JSON.stringify(this);
        Object.keys(this).filter(key => key[0] === "_").forEach(key => {
            json = json.replace(key, key.substring(1));
        });

        return json;
    }
}

let version = new Version();
version.major = 2;
console.log(version.toJsonString()); // {"major":2}



回答2:


based on @Jan-Aagaard solution I have tested this one

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

in order to use the toJSON method




回答3:


I think iterating through the properties and string manipulating is dangerous. I would do using the prototype of the object itself, something like this:

public static toJSONString() : string {
    return JSON.stringify(this, Object.keys(this.constructor.prototype)); // this is version class
}



回答4:


I've written a small library ts-typed, which generate getter/setter for runtime typing purpose. I've faced the same problem when using JSON.stringify(). So i've solved it by adding a kind of serializer, and proposing to implement a kind of toString (in Java) buy calling it toJSON.

Here is an example:

import { TypedSerializer } from 'ts-typed';

export class RuntimeTypedClass {
    private _major: number;

    get major(): number {
       return this._major;
    }

    set major(major: number) {
       this._major = major;
    }
    /**
    * toString equivalent, allows you to remove the _ prefix from props.
    *
    */
    toJSON(): RuntimeTypedClass {
        return TypedSerializer.serialize(this);
    }
}


来源:https://stackoverflow.com/questions/40080473/using-json-stringify-in-conjunction-with-typescript-getter-setter

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