Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

typescript parse json with class and interface

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?

like image 297
Murhaf Sousli Avatar asked Nov 20 '15 16:11

Murhaf Sousli


1 Answers

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.
like image 139
gilamran Avatar answered Sep 19 '22 02:09

gilamran