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?