如何将JSON对象转换为Typescript类

json TypeScript

木嘢

2020-05-25

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

我不想填充一个TypeScript变量(即有一个采用此JSON对象的构造函数)。它很大,因此要在子对象之间按子对象复制所有内容,并按属性复制所有内容将花费大量时间。

更新:但是,您可以将其转换为TypeScript界面!

第4172篇《如何将JSON对象转换为Typescript类》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

5个回答
蓝染大人 2020.05.25

在TypeScript中,您可以使用接口和泛型来进行类型断言,如下所示:

var json = Utilities.JSONLoader.loadFromFile("../docs/location_map.json");
var locations: Array<ILocationMap> = JSON.parse(json).location;

ILocationMap在哪里描述数据的形状。此方法的优点是您的JSON可以包含更多属性,但形状可以满足接口的条件。

希望对您有所帮助!

仲羽蛋蛋 2020.05.25

我发现了一篇关于将JSON通用转换为Typescript类的非常有趣的文章:

http://cloudmark.github.io/Json-Mapping/

您最终得到以下代码:

let example = {
                "name": "Mark", 
                "surname": "Galea", 
                "age": 30, 
                "address": {
                  "first-line": "Some where", 
                  "second-line": "Over Here",
                  "city": "In This City"
                }
              };

MapUtils.deserialize(Person, example);  // custom class
JinJin 2020.05.25

如果您使用的是ES6,请尝试以下操作:

class Client{
  name: string

  displayName(){
    console.log(this.name)
  }
}

service.getClientFromAPI().then(clientData => {

  // Here the client data from API only have the "name" field
  // If we want to use the Client class methods on this data object we need to:
  let clientWithType = Object.assign(new Client(), clientData)

  clientWithType.displayName()
})

但是,遗憾的是,这种方式对嵌套对象无效

GO 2020.05.25

我遇到了同样的问题,并且找到了一个可以完成此工作的库:https : //github.com/pleerock/class-transformer

它是这样的:

let jsonObject = response.json() as Object;
let fooInstance = plainToClass(Models.Foo, jsonObject);
return fooInstance;

它支持嵌套的子级,但是您必须装饰类的成员。

Mandy 2020.05.25

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

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

复制数据的一些示例:

  1. 将AJAX JSON对象复制到现有对象
  2. 将JSON字符串解析为JavaScript中的特定对象原型

本质上,您只是:

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

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android