【发布时间】:2017-02-25 14:52:57
【问题描述】:
我正在尝试找到将我的 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;
}
}
效果很好。但是在 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 || { };
}
我无法让这种方法适用于我的案例,我说body.data 未定义。
这种方法真的有效吗?
编辑:
我的 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"
}
}
]
}
我的服务代码:
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());
}
我的搜索组件代码:
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));
},
() => { }
);
}
编辑 2:
为了让这个案例更简单,我编写了这个简单的代码:
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))返回一个对象列表 -
console.log(MyObject.fromJSON(JSON.parse(json_text)))返回一个 我的对象列表
【问题讨论】:
标签: json object angular casting