如何将JSON对象转换为TypeScript类

如何将JSON对象转换为TypeScript类

本文介绍了如何将JSON对象转换为Typescript类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从远程REST服务器读取了JSON对象.此JSON对象具有Typescript类的所有属性(通过设计).如何将收到的JSON对象转换为var类型?

I read a JSON object from a remote REST server. This JSON object has all the properties of a typescript class (by design). How do I cast that received JSON object to a type var?

我不想填充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.

更新:但是,您可以

推荐答案

您不能简单地将Ajax请求中的原始JavaScript结果转换为原型JavaScript/TypeScript类实例.有许多技术可以做到这一点,并且通常涉及复制数据.除非您创建该类的实例,否则它将没有任何方法或属性.它将仍然是一个简单的JavaScript对象.

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.

如果仅处理数据,则可以将其强制转换为接口(因为它纯粹是编译时结构),这将要求您使用TypeScript类,该类使用数据实例并对该数据实例执行操作数据.

While if you only were dealing with data, you could just do a cast to an interface (as it's purely a compile time structure), this would require that you use a TypeScript class which uses the data instance and performs operations with that data.

复制数据的一些示例:

  1. 将AJAX JSON对象复制到现有Object
  2. 将JSON字符串解析为JavaScript
  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对象转换为Typescript类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 10:19