Angular 2 将 JSON 对象解析为 Angular 类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36456225/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Angular 2 parsing JSON objects into angular classes
提问by zanther
I've been following the Angular2 getting started documentation to get my own app off the ground, I've been successful in retrieving JSON objects from a local file and displaying them in angular2 templates. However currently it relies on the angular classes exactly matching the structure of the objects in my JSON file.
我一直在关注 Angular2 入门文档以启动我自己的应用程序,我已经成功地从本地文件中检索 JSON 对象并将它们显示在 angular2 模板中。但是目前它依赖于与我的 JSON 文件中的对象结构完全匹配的角度类。
Eventually I'll need my app to work with JSON-LD, which has property names such as "@id". I've done some googling and it seems that RxJS might have the functionality I'm looking for but I'm not sure where to start to interupt the automatic binding from some JSON data straight into my angular2 classes, and instead be able to look up something that's labeled as "@id" in the json and set the value of SomeClass.id
最终,我需要我的应用程序使用 JSON-LD,它具有诸如“@id”之类的属性名称。我已经做了一些谷歌搜索,似乎 RxJS 可能具有我正在寻找的功能,但我不确定从哪里开始将一些 JSON 数据的自动绑定直接中断到我的 angular2 类中,而是能够查看在 json 中标记为“@id”的内容并设置 SomeClass.id 的值
Current code that automatically produces an array of a Person class:
当前自动生成 Person 类数组的代码:
getPeople(){
return this._http.get(this._peopleUrl)
.map(response => <Person[]> response.json().data)
.do(data => console.log(data)) //debug to console
.catch(this.handleError);
}
Fine for JSON like this:
像这样的 JSON 很好:
[
{
"id":"1",
"name":"tessa"
},
{
"id":"2",
"name":"jacob"
}
]
But it would obviously fail for JSON like this:
但是对于这样的 JSON,它显然会失败:
[
{
"@id":"1",
"name":"tessa"
},
{
"@id":"2",
"name":"jacob"
}
]
My class is simple (at the moment :-) )
我的课很简单(目前:-))
export class Person {
constructor(
public id:number,
public name:string,
){}
}
Can anyone point me in the right direction for some documentation/examples of mapping complex/tricky json to the classes in angular2?
对于将复杂/棘手的 json 映射到 angular2 中的类的一些文档/示例,任何人都可以指出我正确的方向吗?
回答by zanther
I found the answer in Option 4 of the answer given here: How do I initialize a typescript object with a JSON object
我在此处给出的答案的选项 4 中找到了答案:How do I initialize a typescript object with a JSON object
Hope this helps if anyone lands on this page looking for the same thing!
如果有人在此页面上寻找相同的东西,希望这会有所帮助!

