【问题标题】:typescript parse json with class and interfacetypescript 使用类和接口解析 json
【发布时间】: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


    【解决方案1】:

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

    【讨论】:

    • 成功了,不需要为接口创建自定义类吗?
    • 你不是这个对象的创建者,不要上课。除非你想开始用这个对象做动作(函数)
    • 但是如果我不知道 JSON 将包含什么怎么办?如何为我不知道其内容的对象创建接口?
    • 请记住,TypeScript 仅用于开发时,您的服务器响应将在运行时给出……这意味着您可以通过转换给定的 JSON 来“帮助”自己。不是承诺服务器会返回你所假设的吗?
    • 如果您真的不知道服务器将返回什么 JSON,您只需首先将其键入为 :any,然后检查 json 对象上是否存在属性。之后,您可以将其转换为相应的类型。类似于if(obj.actor) mytypedobject = &lt;actor&gt;obj
    猜你喜欢
    • 2020-12-03
    • 2016-11-10
    • 2015-03-11
    • 1970-01-01
    • 2018-07-11
    • 2018-04-06
    • 2017-08-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多