【发布时间】:2016-02-23 05:42:14
【问题描述】:
我正在尝试使一个类 Post 包含帖子属性,例如“id、title、content ...等。
我想从 JSON 响应初始化类。我正在使用 angular-http 在 typescript 中获取 JSON
在 APP.TS 中:
class AppComponent {
result: { [key: string]: string; };
map: Map<Object,Object>;
constructor(http: Http) {
http.get('http://localhost/wptest/wp-json/wp/v2/posts').subscribe(res => {
this.result = <any>res.json();
this.map = <any>res.json();
console.log(this.result);
console.log(this.map);
});
}
}
注意:
我仍然对哪种类型适合我的 JSON 感到困惑
我读到 typescript 还不支持 Map,但它在这里以 result: {[key:string]: string; };
我在stackoverflow上查了一下,发现了这个问题how to cast a json object to a typescript,答案和typescript无关。
在另一个问题Can I create a TypeScript type and use that when AJAX returns JSON data?
答案是关于在 typescript 中创建接口。 (我不太明白。)
我还发现这个站点为json2ts 从 JSON 生成 typescript 接口,所以我尝试了我的 json 并得到了这个:
declare module namespace {
export interface Guid {
rendered: string;
}
export interface Title {
rendered: string;
}
export interface Content {
rendered: string;
}
export interface Excerpt {
rendered: string;
}
export interface Self {
href: string;
}
export interface Collection {
href: string;
}
export interface Author {
embeddable: boolean;
href: string;
}
export interface Reply {
embeddable: boolean;
href: string;
}
export interface VersionHistory {
href: string;
}
export interface Links {
self: Self[];
collection: Collection[];
author: Author[];
replies: Reply[];
}
export interface RootObject {
id: number;
date: Date;
guid: Guid;
modified: Date;
modified_gmt: Date;
slug: string;
type: string;
link: string;
title: Title;
content: Content;
excerpt: Excerpt;
author: number;
featured_image: number;
comment_status: string;
ping_status: string;
sticky: boolean;
format: string;
_links: Links;
}
}
现在我的 JSON 有了一个 typescript 接口,但我不知道下一步该做什么!
问:这是在 typescript 中将 JSON 解析为类对象的正确方法吗?如果是,下一步用数据初始化类是什么?
【问题讨论】:
标签: json interface typescript