结合使用JSON.stringify和TypeScript getter/setter [英] Using JSON.stringify in conjunction with TypeScript getter/setter
问题描述
我在TypeScript中使用getter/setter访问器.由于不可能为变量和方法使用相同的名称,因此我开始在变量前面加一个短横线,就像在许多示例中所做的那样:
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;
}
现在,当我使用JSON.stringify()方法将对象转换为JSON字符串时,它将使用变量名作为键:_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.
由于我不希望JSON文件的所有键都带有一个短横线作为前缀,因此是否有可能使TypeScript使用getter方法的名称(如果有)?还是有其他方法可以使用getter/setter方法,但仍会产生干净的JSON输出?
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?
我知道有一些方法可以在将JSON密钥写入字符串输出之前手动对其进行修改.我很好奇是否有更简单的解决方案.
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.
推荐答案
否,您不能让JSON.stringify
使用getter/setter名称而不是属性名称.
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}
这篇关于结合使用JSON.stringify和TypeScript getter/setter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!