Vingtoft
Vingtoft

Reputation: 14636

Whats the easiest way to create a TypeScript object with JSON as input?

In Angular2 (TypeScript) I have a class with the following constructor:

 export class DataModel {
    constructor(public date_of_visit: string,
                public gender: boolean,
                public year_of_birth: number,
                public height: number,
                public weight: number){}
 }

I have the following JSON object:

json = {"date_of_visit": "23/09/2016", "gender": 1, "year_of_birth": 1975, "height":185, "weight": 85}

Question: Whats the easiest way to create a DataModel instance with the JSON data as input? Something like new DataModel(**json)

Upvotes: 1

Views: 103

Answers (2)

Pradeep
Pradeep

Reputation: 3276

Casting should get you through:

let model: DataModel = {"date_of_visit": "23/09/2016", "gender": 1, "year_of_birth": 1975, "height":185, "weight": 85} as DataModel;

Upvotes: 0

Marin Relatic
Marin Relatic

Reputation: 238

For compile time casting, this will do:

let dataModel = {"date_of_visit": "23/09/2016", "gender": 1, "year_of_birth": 1975, "height":185, "weight": 85} as DataModel;

Upvotes: 1

Related Questions