typescript用类和接口解析json [英] typescript parse json with class and interface

查看:237
本文介绍了typescript用类和接口解析json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力使课程发布包含帖子属性,例如id,title,content ...等。



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





  class AppComponent {result:{[key:string]:string;}; map:Map< Object,对象> ;;构造函数(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
我读到打字稿不是支持地图,但它在这里工作为结果:{[key:string]:string;我想找到这个问题如何将json对象转换为打字稿,答案无关打字稿。



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



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



我还发现这个网站是 json2ts 从JSON生成打字稿接口,所以我尝试了我的json,我得到了这个:



  declare module namespace {export interface Guid {rendered:string; } export interface Title {rendered:string; } export interface Content {rendered:string; } export interface摘录{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链接{self:Self []; collection:Collection [];作者:作者[];回复:回复[];导出接口RootObject {id:number;日期:日期; guid:Guid;修改日期; modified_gmt:日期; slug:string; type:string; link:string;标题:标题;内容:内容;摘录:摘录;作者:号码; featured_image:number; comment_status:string; ping_status:string; sticky:boolean;格式:字符串; _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; //错误:RootObject接口中不存在age 
this.id =Hello; //错误,id是一个数字,你试着把字符串放入其中。
this.id = 100; //会没事的


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

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

in 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 Map yet, however it is working here as 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.

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

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

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

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!

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?

解决方案

You should definitely use interfaces to describe your DTO (Data Transfer Object). It looks like the json2ts did 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:

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:

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.

这篇关于typescript用类和接口解析json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆