【问题标题】:Angular2 parsing from JSON to objectAngular2 从 JSON 解析到对象
【发布时间】: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(&lt;MyObject[]&gt;JSON.parse(json_text)) 返回一个对象列表
  • console.log(MyObject.fromJSON(JSON.parse(json_text))) 返回一个 我的对象列表

【问题讨论】:

    标签: json object angular casting


    【解决方案1】:

    我对这个话题很晚了,但发现自己陷入了同样的问题。我正在学习 Angular 并希望将从 HTTP 服务器接收到的 JSON 转换为我的模型对象。

    服务类

    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 Model 用于保存 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;
    }
    

    就是这样。我正在使用 Angular 6 将 JSON 解析为对象

    【讨论】:

      【解决方案2】:

      这是因为在 Angular 教程中,json 在 data 属性中。

      如教程中所述

      不对服务器 API 做任何假设。并非所有服务器都返回 具有数据属性的对象。

      如果你没有用任何属性包装你的 json,你可以使用

      private extractData(res: Response) {
        let body = res.json();
        return body || { }; //<--- not wrapped with data
      }
      

      更新:

      组件代码

       onSearch(terms: string) {    
          this.searchService.search(this.user, terms).subscribe(
            (response: SearchResponse) => {    // <--- cast here   
                console.log(response); 
            },
            error => {
                console.log(JSON.stringify(error));
            },
            () => { }
          );
       }
      

      【讨论】:

      • 谢谢。通过您的修改,它会返回Object 的列表,而不是User 的列表。有办法解决吗?
      • 尝试取消注释第二张地图.map((res) =&gt; {res.result = &lt;User&gt;res.result});
      • 它返回一个空的json {}
      • 什么时候得到对象数组?当您订阅组件或映射服务时?
      • 当我在组件订阅时
      猜你喜欢
      • 2017-07-27
      • 1970-01-01
      • 1970-01-01
      • 2012-05-17
      • 2016-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多