Angular2 从 JSON 解析到对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40072543/
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
Angular2 parsing from JSON to object
提问by Ben
I'm trying to find the best way to cast my json object to Typescript object. I have a http get service which returns a list of user. My current version works, I have added from JSON function to all my model classes to make the mapping works:
我试图找到将我的 json 对象转换为 Typescript 对象的最佳方法。我有一个 http get 服务,它返回一个用户列表。我当前的版本有效,我已将 JSON 函数添加到我的所有模型类以使映射有效:
export class User {
constructor(
public pk: number,
public username: string,
public first_name: string,
public last_name: string,
public email: string,
public profile: UserProfile, ) {
}
static fromJSON(json: any): User {
let user = Object.create(User.prototype);
Object.assign(user, json);
user.profile = UserProfile.fromJSON(json.profile);
return user;
}
}
That works well. But there is something I don't get in the angular 2 doc. On the heroes tutorial, the JSON is automatically casted to object this way:
这很好用。但是我在 angular 2 文档中没有得到一些东西。在英雄教程中,JSON 会以这种方式自动转换为对象:
getHeroes (): Observable<Hero[]> {
return this.http.get(this.heroesUrl)
.map(this.extractData)
.catch(this.handleError);
}
private extractData(res: Response) {
let body = res.json();
return body.data || { };
}
I can't get this method to work on my case, I says that body.datais undefined.
Does this method really works?
我无法让这种方法适用于我的案例,我说这body.data是未定义的。这个方法真的有效吗?
EDIT:
编辑:
My http service doesn't returns an array of users. It returns a page which contains an array of users in its 'results' property.
我的 http 服务不返回用户数组。它返回一个页面,该页面在其“结果”属性中包含一组用户。
{
"count": 2,
"next": null,
"previous": null,
"results": [
{
"pk": 48,
"first_name": "Jon",
"last_name": "Does",
"profile": {
"pk": 46,
"gender": "U"
}
},
{
"pk": 47,
"first_name": "Pablo",
"last_name": "Escobar",
"profile": {
"pk": 45,
"gender": "M"
}
}
]
}
My service code:
我的服务代码:
private extractData(res: Response) {
let body = res.json().results;
return body || {}; //<--- not wrapped with data
}
search(authUser: AuthUser, terms: string): Observable<User[]> {
let headers = new Headers({
'Content-Type': 'application/json',
'X-CSRFToken': this.cookiesService.csrftoken,
'Authorization': `Token ${authUser.token}`
});
let options = new RequestOptions({ headers: headers });
return this.http.get(environment.server_url + 'user/?search=' + terms, options)
.map(this.extractData);
// .map((response: Response) => response.json());
}
My search component code:
我的搜索组件代码:
onSearch(terms: string) {
this.searchService.search(this.user, terms).subscribe(
response => {
console.log(response); // Return array of object instead of array of user
},
error => {
console.log(JSON.stringify(error));
},
() => { }
);
}
EDIT 2:
编辑2:
To make this case easier, I've wrote this simple code:
为了使这个案例更容易,我写了这个简单的代码:
test(){
let json_text=` [
{
"id": 1,
"text": "Jon Doe"
},
{
"id": 1,
"text": "Pablo Escobar"
}
]`;
console.log(<MyObject[]>JSON.parse(json_text)); // Array of objects
console.log(MyObject.fromJSON(JSON.parse(json_text))); // Array of 'MyObject'
}
export class MyObject{
id: number;
text: string;
static fromJSON(json: any): MyObject {
let object = Object.create(MyObject.prototype);
Object.assign(object, json);
return object;
}
}
console.log(<MyObject[]>JSON.parse(json_text))returns a list of Objectsconsole.log(MyObject.fromJSON(JSON.parse(json_text)))returns a list of MyObject
console.log(<MyObject[]>JSON.parse(json_text))返回对象列表console.log(MyObject.fromJSON(JSON.parse(json_text)))返回 MyObject 的列表
回答by Sefa
It's because in Angular tutorial, json is in the data property.
这是因为在 Angular 教程中,json 位于 data 属性中。
As stated in the tutorial
如教程中所述
Make no assumptions about the server API. Not all servers return an object with a data property.
不对服务器 API 做任何假设。并非所有服务器都返回具有数据属性的对象。
If you are not wrapping your json with any property you can just use
如果您没有使用任何属性包装 json,则可以使用
private extractData(res: Response) {
let body = res.json();
return body || { }; //<--- not wrapped with data
}
Update:
更新:
Component code
组件代码
onSearch(terms: string) {
this.searchService.search(this.user, terms).subscribe(
(response: SearchResponse) => { // <--- cast here
console.log(response);
},
error => {
console.log(JSON.stringify(error));
},
() => { }
);
}
回答by Geek
I am quite late to this topic but found my self into the same issue . I am learning Angular and want to convert JSON received from HTTP server to my model object .
我很晚才开始讨论这个话题,但发现自己也遇到了同样的问题。我正在学习 Angular 并希望将从 HTTP 服务器收到的 JSON 转换为我的模型对象。
Service Class
服务等级
var ele:User;
let k=this.http.get<User>(url).subscribe(data => {
ele=data;
console.log(ele.count);
console.log(ele.results[0].first_name);
console.log(ele.results[0].profile.gender);
}
);
My Modelfor holding the information of JSON
我的模型用于保存 JSON 的信息
export interface User{
count: string;
next: string;
previous: string;
results: Result[];
}
export interface Result{
pk: string;
first_name: string;
last_name: string;
profile:Profile;
}
export interface Profile{
pk: string;
gender:string;
}
And this is it. I am using Angular 6 for parsing JSON to Object
就是这样。我正在使用 Angular 6 将 JSON 解析为对象

