Search code examples
jsonclassinterfacetypescript

Typescript create a class from json


I have an interface IPost and a class Post, I want to create Post from json data, in Post constructor I get the json response where the interface IPost matches it.

I mean IPost interface is generated by this great tool json2ts

json2ts : generate TypeScript interfaces from JSON

import { IPost, Title, Guid, Content, Excerpt, Embedded, Links } from './Ipost.ts';

export class Post implements IPost {
    Id: number;
    Date: string;
    DateGmt: string;
    Guid: Guid;
    Modified: string;
    ModifiedGmt: string;
    Slug: string;
    Type: string;
    Link: string;
    Title: Title;
    Content: Content;
    Excerpt: Excerpt;
    Author: number;
    FeaturedImage: number;
    CommentStatus: string;
    PingStatus: string;
    Sticky: boolean;
    Format: string;
    Links: Links;
    Embedded: Embedded;

    constructor(json: any) {
        var self = this;
        json.subscribe(res => {
            var jsonRes: any = res.json();
            self = jsonRes;        //something like this
        });
    }
}

Can I assign the class Post to json directly since json is described the same as Post class!

Is there any other ways than assigning each property to its peer from json?


Solution

  • Just as you would JavaScript you'll have to iterate over each value, and assign that value to self, using standard loop. Assigning to self in your case, simply changes the value of self to the json value, it doesn't make any changes this itself.

    json.subscribe(res => {
        let json = res.json();
        for (var prop in obj) {
            if( obj.hasOwnProperty( prop ) ) {
                this[prop] = obj[prop];
            }
        }
    });
    

    NOTE: => binds this to the outer context (for example the class you're working with) to this, so that you do not need to the intermediate self variable.