我从远程睡觉服务器读取了一个json对象.此JSON对象具有TypeScript类的所有属性(根据设计).如何将接收到JSON对象转换为类型变量?

I don't want to populate a typescript var (ie have a constructor that takes this JSON object). It's large and copying everything across sub-object by sub-object & property by property would take a lot of time.

Update: You can however cast it to a typescript interface!

推荐答案

You can't simple cast a plain-old-JavaScript result from an Ajax request into a prototypical JavaScript/TypeScript class instance. There are a number of techniques for doing it, and generally involve copying data. Unless you create an instance of the class, it won't have any methods or properties. It will remain a simple JavaScript object.

如果只处理数据,则可以对接口执行强制转换(因为它纯粹是编译时 struct ),这需要使用一个TypeScript类,该类使用数据实例并对该数据执行操作.

复制数据的一些示例:

  1. Copying AJAX JSON object into existing Object
  2. Parse JSON String into a Particular Object Prototype in JavaScript

本质上,你只是:

var d = new MyRichObject();
d.copyInto(jsonResult);

Json相关问答推荐

如何在VegaLite中应用Times New Roman,CaliBiri字体

Vega Lite中的图例对齐

修改Deneb图表中工具提示的字体大小

Oracle plsql:如何将json文件加载到嵌套表中

如何在VB6中将字符串转换或解码为可读格式?

在Databricks中如何将JSON文件作为字典读取

如何在 Apps 脚本中循环遍历 JSON 响应

我无法将来自 API 的数据显示到 FlatList 中,但我在 console.log 中看到了它.问题是什么?

从 json 对象中过滤掉所有出现的给定属性

Angular 2/Web Api - json 解析错误语法错误意外结束输入

JSON.NET 中特定对象的自定义转换

SyntaxError:Object.parse(本机)AngularJS中的意外标记o

没有很多类的 GSON 解析

Jackson 中的 readValue 和 readTree:何时使用哪个?

使用 simplejson 序列化简单类对象的最简单方法?

通过 JSON 发送 HTML 代码

与classic 规范化表相比,postgres JSON 索引是否足够高效?

使用新的 Net Core 3.0 Json 时忽略属性

JSON - 是否有任何 XML CDATA 类似功能?

按键值过滤 JSON