[英]Whats the easiest way to create a TypeScript object with JSON as input?
In Angular2 (TypeScript) I have a class with the following constructor:在 Angular2 (TypeScript) 中,我有一个具有以下构造函数的类:
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 对象:
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?问题:使用 JSON 数据作为输入创建 DataModel 实例的最简单方法是什么? Something like
new DataModel(**json)
类似于
new DataModel(**json)
对于编译时转换,这将执行以下操作:
let dataModel = {"date_of_visit": "23/09/2016", "gender": 1, "year_of_birth": 1975, "height":185, "weight": 85} as DataModel;
铸造应该让你通过:
let model: DataModel = {"date_of_visit": "23/09/2016", "gender": 1, "year_of_birth": 1975, "height":185, "weight": 85} as DataModel;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.