简体   繁体   English

使用 JSON 作为输入创建 TypeScript 对象的最简单方法是什么?

[英]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.

相关问题 在Angular 2打字稿中将JSON转换为通用Object []的最佳方法是什么? - Whats the best way to cast JSON to generic Object[] in angular 2 typescript? 将大 JSON 从对象数组包装到 object 中的“数据”在 typeScript 中的最简单方法是什么 - What's the easiest way to wrap a big JSON from array of objects to an object with “data” in typeScript 将 freemarker 对象呈现为 JSON 的最简单方法是什么? - What is the easiest way to render a freemarker object as JSON? Kotlin - 创建通用数据对象以转换为 API 请求的 JSON 的最简单方法是什么? - Kotlin - What is the easiest way to create a generic data object to transform into JSON for API requests? 通过 Javascript 交互复杂 JSON 对象的最简单方法 - Easiest way to interate over a complex JSON object via Javascript 利用Coldfusion返回的json对象的最简单方法(来自查询) - Easiest way to utilize coldfusion returned json object (from query) 在JavaScript中修复此JSON对象字符串的最干净的方法是什么? - Whats the cleanest way to repair this JSON object string in javascript? 解析JSON响应的最简单方法 - Easiest way to parse JSON response 解析/读取Json的最简单方法 - The Easiest Way To Parse/Read Json 将 pcap 转换为 JSON 的最简单方法 - Easiest way to convert pcap to JSON
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM