如何将json对象反序列化为angular模型

时间:2019-05-16 10:42:42

标签: angular typescript

我正在尝试反序列化包含总计数和用户列表的json响应对象。我是否需要在用户模型中存储totalcount

我尝试使用地图和管道,但是无法弄清楚模型接口中的数据

"total_count": 5,
"incomplete_results": false,
"items": [
 {
   "login": "mojombo",
   "id": 1,
   "node_id": "MDQ6VXNlcjE=",
   "avatar_url": "https://avatars0.githubusercontent.com/u/1?v=4",
   "gravatar_id": "",
   "url": "https://api.github.com/users/mojombo",
   "html_url": "https://github.com/mojombo",
   "followers_url": "https://api.github.com/users/mojombo/followers",
   "following_url": "https://api.github.com/users/mojombo/following{/other_user}",
   "gists_url": "https://api.github.com/users/mojombo/gists{/gist_id}",
   "starred_url": "https://api.github.com/users/mojombo/starred{/owner}{/repo}",
   "subscriptions_url": "https://api.github.com/users/mojombo/subscriptions",
   "organizations_url": "https://api.github.com/users/mojombo/orgs",
   "repos_url": "https://api.github.com/users/mojombo/repos",
   "events_url": "https://api.github.com/users/mojombo/events{/privacy}",
   "received_events_url": "https://api.github.com/users/mojombo/received_events",
   "type": "User",
   "site_admin": false,
   "score": 97.55435
 },
 {
   "login": "tmcw",
   "id": 32314,
   "node_id": "MDQ6VXNlcjMyMzE0",
   "avatar_url": "https://avatars2.githubusercontent.com/u/32314?v=4",
   "gravatar_id": "",
   "url": "https://api.github.com/users/tmcw",
   "html_url": "https://github.com/tmcw",
   "followers_url": "https://api.github.com/users/tmcw/followers",
   "following_url": "https://api.github.com/users/tmcw/following{/other_user}",
   "gists_url": "https://api.github.com/users/tmcw/gists{/gist_id}",
   "starred_url": "https://api.github.com/users/tmcw/starred{/owner}{/repo}",
   "subscriptions_url": "https://api.github.com/users/tmcw/subscriptions",
   "organizations_url": "https://api.github.com/users/tmcw/orgs",
   "repos_url": "https://api.github.com/users/tmcw/repos",
   "events_url": "https://api.github.com/users/tmcw/events{/privacy}",
   "received_events_url": "https://api.github.com/users/tmcw/received_events",
   "type": "User",
   "site_admin": false,
   "score": 82.624016
 }
export interface User{
  id:string;
  url:string;
  login:string; 
}

我还应该在哪里以及如何存储总数

2 个答案:

答案 0 :(得分:1)

要投射到模型,请尝试以下操作:

const model = Object.create(YourModel.prototype)
Object.assign(model, JSON.parse(jsonString))

 var model = new YourModel();
 model.copyInto(JSON.parse(jsonString));

要包括数量,您可以创建一个新的自定义模型:

CustomModel

{
  yourModel: YourModel;
  count:number;
}

然后:

const model = Object.create(CustomModel.prototype)
Object.assign(model, JSON.parse(jsonString))

答案 1 :(得分:1)

我将使用一个单独的变量来存储total_count。

TS代码:

user: User[] = [];
totalCount: any;

constructor() {
    this.user = this.data.items as User[];
    this.totalCount = this.data.total_count;
}

WORKING_DEMO