簡體   English   中英

typescript用類和接口解析json

[英]typescript parse json with class and interface

我試圖做一個類崗位包含交的屬性,如“ID,標題,內容...等。

我想從JSON響應初始化類。 我正在使用angular-http來獲取打字稿中的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哪個是正確的類型我讀到的打字稿還沒有支持Map ,但是它在這里工作的result: {[key:string]: string; }; result: {[key:string]: string; };

我試着查看stackoverflow,我發現這個問題如何將一個json對象轉換為打字稿 ,答案與打字稿無關。

在另一個問題中我可以創建一個TypeScript類型並在AJAX返回JSON數據時使用它嗎?

答案是談論在打字稿中創建接口。 (我不太明白。)

我還發現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有一個打字稿界面,但我不知道下一步該做什么!

問:這是將JSON解析為打字稿中的類對象的正確方法嗎? 如果是,使用數據初始化類的下一步是什么?

您絕對應該使用接口來描述您的DTO(數據傳輸對象)。 看起來json2ts在描述你的JSON結構方面做得很好。 現在,因為http服務為您創建了對象,所以您不必創建新對象...您只需將其強制轉換為您的界面,如下所示:

class AppComponent {
  dataFromServer : RootObject;

  http.get('http://localhost/wptest/wp-json/wp/v2/posts').subscribe(res => {
    this.dataFromServer = <RootObject>res.json();
  });
}

從那時起,當您嘗試訪問來自服務器的任何數據時,TypeScript將防止您犯任何錯誤。 例如:

this.dataFromServer.age = 45; // Error: age doesn't exist in the RootObject interface
this.id = "Hello"; // Error, id was is a number, and you try to put string into it.
this.id = 100; // will be just fine.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM