TypeScript中的Json属性别名 [英] Json property alias in typescript
问题描述
假设我要从Visual Studio TFS
获取数据,并且响应(作为json)采用这种格式:
Let's say I want to get a data from Visual Studio TFS
and the response (as json) is in this kind of format:
{
"Microsoft.VSTS.Scheduling.StoryPoints": 3.0,
// ......
}
属性名称中有点.通过阅读其他问题,我发现可以使用这样的接口在Typescript中读取json
There's dot in the property name. Reading from other questions I found out that I can read that json in typescript by using an interface like this
export interface IStory { // I don't think this kind of interface do me any help
"Microsoft.VSTS.Scheduling.StoryPoints": number
}
然后我可以使用带有以下语法的属性:
And then I can use the property with this syntax:
var story = GetStoryFromTFS();
console.log(story["Microsoft.VSTS.Scheduling.StoryPoints"]);
但是我不希望这样调用该属性,因为智能感知将无法帮助我找到要使用的属性(因为我使用字符串来调用该属性).
But I'd prefer not to call the property like this, since the intellisense won't able to help me finding which property I want to use (because I call the property using a string).
在C#中,有一个JsonProperty
属性,使我能够创建如下模型:
In C# there is a JsonProperty
attribute which enable me to create a model like this:
public class Story
{
[JsonProperty(PropertyName = "Microsoft.VSTS.Scheduling.StoryPoints")]
public double StoryPoints { get; set; }
}
然后我可以通过这种方式使用该属性:
And then I can use the property this way:
var story = GetStoryFromTFS();
Console.WriteLine(story.StoryPoints);
通过这种方式,智能感知将能够帮助我找到要使用的属性.
This way the intellisense will able to help me finding which property I want to use.
打字稿中是否存在类似于JsonProperty
属性的内容?还是有其他更好的方法可以在打字稿中实现呢?
Is there something like JsonProperty
attribute in typescript? Or is there any other, better way, to achieve this in typescript?
推荐答案
您有很多选择.请记住,所有这些选项都要求您将原始数据传递给将要访问它的类.
You have many options. Just keep in mind that all of these options require you to pass the original data to the class that will access it.
映射值.
class StoryMap {
constructor(data: IStory) {
this.StoryPoints = data["Microsoft.VSTS.Scheduling.StoryPoints"];
}
StoryPoints: number;
}
包装数据.
class StoryWrap {
constructor(private data: IStory) {}
get StoryPoints(): number { return this.data["Microsoft.VSTS.Scheduling.StoryPoints"] };
}
构建一个装饰器以映射数据.
Build a decorator to map the data.
function JsonProperty(name: string) {
return function DoJsonProperty(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
descriptor.get = function () {
return this.data[name];
}
descriptor.set = function (value) {
this.data[name] = value;
}
}
}
class StoryDecorator
{
constructor(private data: IStory) {}
@JsonProperty("Microsoft.VSTS.Scheduling.StoryPoints")
get StoryPoints(): number { return 0 };
}
这篇关于TypeScript中的Json属性别名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!