typescript用类和接口解析json

前端之家收集整理的这篇文章主要介绍了typescript用类和接口解析json前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试创建一个类Post包含帖子属性,如“id,title,content …等.

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

在APP.TS:

  1. class AppComponent {
  2.  
  3. result: { [key: string]: string; };
  4. map: Map<Object,Object>;
  5. constructor(http: Http) {
  6. http.get('http://localhost/wptest/wp-json/wp/v2/posts').subscribe(res => {
  7. this.result = <any>res.json();
  8. this.map = <any>res.json();
  9. console.log(this.result);
  10. console.log(this.map);
  11. });
  12. }
  13. }

注意:
我仍然感到困惑的是哪个是我的JSON的正确类型
我读过打字稿不支持Map,但是它在这里工作:{[key:string]:string; };

我试着查看stackoverflow,我发现这个问题how to cast a json object to a typescript,答案与打字稿无关.

在另一个问题Can I create a TypeScript type and use that when AJAX returns JSON data?

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

我还发现json2ts的这个站点从JSON生成了typescript接口,所以我尝试了我的json,我得到了这个:

  1. declare module namespace {
  2.  
  3. export interface Guid {
  4. rendered: string;
  5. }
  6.  
  7. export interface Title {
  8. rendered: string;
  9. }
  10.  
  11. export interface Content {
  12. rendered: string;
  13. }
  14.  
  15. export interface Excerpt {
  16. rendered: string;
  17. }
  18.  
  19. export interface Self {
  20. href: string;
  21. }
  22.  
  23. export interface Collection {
  24. href: string;
  25. }
  26.  
  27. export interface Author {
  28. embeddable: boolean;
  29. href: string;
  30. }
  31.  
  32. export interface Reply {
  33. embeddable: boolean;
  34. href: string;
  35. }
  36.  
  37. export interface VersionHistory {
  38. href: string;
  39. }
  40.  
  41. export interface Links {
  42. self: Self[];
  43. collection: Collection[];
  44. author: Author[];
  45. replies: Reply[];
  46. }
  47.  
  48. export interface RootObject {
  49. id: number;
  50. date: Date;
  51. guid: Guid;
  52. modified: Date;
  53. modified_gmt: Date;
  54. slug: string;
  55. type: string;
  56. link: string;
  57. title: Title;
  58. content: Content;
  59. excerpt: Excerpt;
  60. author: number;
  61. featured_image: number;
  62. comment_status: string;
  63. ping_status: string;
  64. sticky: boolean;
  65. format: string;
  66. _links: Links;
  67. }
  68. }

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

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

解决方法

您绝对应该使用接口来描述您的DTO(数据传输对象).
看起来json2ts在描述你的JSON结构方面做得很好.
现在,因为http服务为您创建了对象,所以您不必创建新对象…您只需将其强制转换为您的界面,如下所示:
  1. class AppComponent {
  2. dataFromServer : RootObject;
  3.  
  4. http.get('http://localhost/wptest/wp-json/wp/v2/posts').subscribe(res => {
  5. this.dataFromServer = <RootObject>res.json();
  6. });
  7. }

从那时起,当您尝试访问来自服务器的任何数据时,TypeScript将防止您犯任何错误.例如:

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

猜你在找的JavaScript相关文章