打字稿用类和接口解析json

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33831711/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 18:09:47  来源:igfitidea点击:

typescript parse json with class and interface

jsoninterfacetypescript

提问by Murhaf Sousli

I'm trying to make a class Postcontains post attributes such as "id, title, content ...etc.

我正在尝试让一个类Post包含诸如“id、标题、内容......等”的帖子属性。

I want to initialize the class from a JSON response. I'm using angular-http to get JSON in typescript

我想从 JSON 响应初始化类。我正在使用 angular-http 在打字稿中获取 JSON

in APP.TS:

在 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);     
    });
  }
}

note: I'm still confused about which is the right type for my JSON I read that typescript is not supporting Mapyet, however it is working here as result: {[key:string]: string; };

注意:我仍然对哪种类型适合我的 JSON 感到困惑我读到打字稿还不支持Map,但是它在这里工作result: {[key:string]: string; };

I tried to look up on stackoverflow, I found this question how to cast a json object to a typescript, the answer has nothing to do with typescript.

我试图在 stackoverflow 上查找,我发现了这个问题how to cast a json object to a typescript,答案与 typescript 无关。

in another question Can I create a TypeScript type and use that when AJAX returns JSON data?

在另一个问题中,我可以创建 TypeScript 类型并在 AJAX 返回 JSON 数据时使用它吗?

the answer is talking about creating interfaces in typescript. (which I didn't quite understand it.)

答案是谈论在打字稿中创建接口。(我不太明白。)

I also found this site for json2tsgenerates typescript interfaces from JSON, so I tried my json and I got this:

我还发现这个json2ts站点从 JSON 生成打字稿接口,所以我尝试了我的 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;
    }
}

Now I've got a typescript interface for my JSON, but I don't know what to do next!

现在我的 JSON 有了一个打字稿接口,但我不知道下一步该怎么做!

Q: Is this the right way to parse JSON to a class object in typescript? if yes what is the next step to get the class initialized with the data?

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

回答by gilamran

You should definitely use interfaces to describe your DTO (Data Transfer Object). It looks like the json2tsdid a good job in describing your JSON structure. Now, because the http service created the object for you, you don't have to create a new one... you only have to cast it to your interface, something like in the following lines:

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

From that point TypeScript will guard you from doing any mistakes when you try to access any data that came from the server. For example:

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