1

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)

Vingtoft
  • 13,368
  • 23
  • 86
  • 135
  • Possible duplicate of [JSON to TypeScript class instance?](http://stackoverflow.com/questions/29758765/json-to-typescript-class-instance) – madreason Oct 12 '16 at 11:42

2 Answers2

1

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;
Marin Relatic
  • 238
  • 2
  • 9
  • FYI, this is a type-_assertion_, which is a compile-time construct, and not a type-_cast_, which would be a runtime-time construct. This effectively means that the object created from parsing the JSON will be an `Object` instance at runtime, and not a `DataModel` instance. This is fine as long as you don't use `instanceof`, or define methods, getters, setters, or anything that is not inherently present in the parsed JSON itself. – John Weisz Oct 11 '16 at 11:43
  • Thanks for clarifying that @JohnWhite. I think the answer Im looking for is type-cast, because I need to call methods of DataModel. Can you show an example of this? – Vingtoft Oct 11 '16 at 11:53
  • I think I found the answer here: http://stackoverflow.com/questions/32167593/how-to-do-runtime-type-casting-in-typescript – Vingtoft Oct 11 '16 at 11:54
  • 1
    IMO, this is a complete unknown in TypeScript for now. There is no standardized methodology for doing an actual type-cast, which can be credited to the relatively young age of TypeScript, and that one of its goals is minimizing any runtime overhead. However, there's an experimental project I started working on, [TypedJSON](https://github.com/JohnWhiteTB/TypedJSON), which does exactly what you are looking for: creating a user-defined class instance from JSON. It has its limitations, but it is solid for general use, and its syntax is extremely lightweight. I can post an answer with it. – John Weisz Oct 11 '16 at 12:01
  • I'll take a look at your project, thanks for your guidance. – Vingtoft Oct 11 '16 at 12:05
0

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;
Pradeep
  • 3,258
  • 1
  • 23
  • 36