[英]Instantiating a TypeScript class from a JSON array
This question is maybe not 100% original but the questions/answers I've found so far seem to neglect a certain elephant in the room. 这个问题可能不是100%原始的,但到目前为止我发现的问题/答案似乎忽略了房间里的某个大象。
I have a situation which I'll simplify for example's sake. 例如,我有一种情况可以简化。 Let's say I have the following JSON response: 假设我有以下JSON响应:
[
{
"place": {
"name": "The Cottage",
"rating": 4
}
},
{
"place": {
"name": "El Burrito Loco",
"rating": 5
}
}
]
Then let's say I want to have a Typescript class called Place
. 然后,假设我要创建一个名为Place
的Typescript类。 If I instantiate each element as a Place
, I have this stupid situation: 如果我将每个元素都实例化为Place
,则会出现以下愚蠢的情况:
<!-- this is an Angular template -->
<ul>
<li *ngFor="let place of places">{{ place.place.name }}</li>
</ul>
What I would prefer, of course, is {{ place.name }}
rather than {{ place.place.name }}
. 当然,我更希望使用{{ place.name }}
而不是{{ place.place.name }}
。
So my question is: how can I transform a JSON response to match my data model ? 所以我的问题是: 如何转换JSON响应以匹配我的数据模型 ?
I've already seen questions/answers like this one . 我已经看到过类似这样的问题/答案。
What confuses me is that a) I imagine that this transformation desire is an incredibly common one, and b) all the answers I've found so far seem to involve a ton of hacky boilerplate (no offense). 令我感到困惑的是:a)我认为这种转变欲望是一种非常普遍的欲望,并且b)到目前为止,我发现的所有答案似乎都涉及大量的骇人听闻的样板(没有冒犯性)。
So what's the deal, does everybody just copy and paste all this boilerplate into their apps to meet what must be a very common need, and the TypeScript (or Angular) developers just didn't come up with a way to meet this need with the language or framework? 那么这是怎么回事, 每个人都只是复制所有这些样板并将其粘贴到他们的应用程序中来满足必须非常普遍的需求吗,而TypeScript(或Angular)开发人员并没有想出一种方法来满足这种需求。语言或框架? That doesn't seem likely. 这似乎不太可能。 It's very confusing. 这非常令人困惑。
Any insight is very much appreciated. 非常感谢任何见解。
I can think of simple map function over API call observable, which will create desired object structure in Place
object model format. 我可以想到可观察到的API调用上的简单映射函数,它将以Place
对象模型格式创建所需的对象结构。
this.dataService.getPlaces()
.map(data => data.json())
.map(items => items.map(
item => <Place>({item.place.name, item.place})
)
);
JSON.parse
actually supports an optional reviver
argument that allows you to control the creation of any given property during the deserialization process. JSON.parse
实际上支持一个可选的reviver
参数,该参数允许您在反序列化过程中控制任何给定属性的创建。 You should be able to use that to create an instance of your class. 您应该能够使用它来创建您的类的实例。
Here's what I ended up doing. 这就是我最终要做的。 Thanks to Pankaj Parkar for providing some clues that led me here. 感谢Pankaj Parkar提供的一些线索将我带到了这里。
getList(): Observable<Place[]> {
return this.http.get(this.placesUrl)
.map(response => response.json().data)
.map(data => data.map((item) => {
return <Place>({
name: item.place.name,
place: item.place
});
}));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.