typescript用类和接口解析json

Mur*_*sli 9 json interface typescript

我试图做一个类帖子包含交的属性,如"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);     
    });
  }
}
Run Code Online (Sandbox Code Playgroud)

注意:我仍然感到困惑的是我的JSON哪个是正确的类型我读过打字稿还没有支持Map,但它在这里工作如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;
    }
}
Run Code Online (Sandbox Code Playgroud)

现在我的JSON有一个打字稿界面,但我不知道下一步该做什么!

问:这是将JSON解析为打字稿中的类对象的正确方法吗?如果是,使用数据初始化类的下一步是什么?

gil*_*ran 17

您绝对应该使用接口来描述您的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();
  });
}
Run Code Online (Sandbox Code Playgroud)

从那时起,当您尝试访问来自服务器的任何数据时,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.
Run Code Online (Sandbox Code Playgroud)