我从远程REST服务器读取了一个JSON对象。这个JSON对象具有typescript类的所有属性(根据设计)。我如何转换收到的JSON对象的类型var?

我不想填充一个typescript变量(即有一个构造函数,以这个JSON对象)。它很大,在子对象和属性之间复制所有内容将花费大量时间。

更新:你可以将它转换为typescript接口!


当前回答

我也遇到过类似的需求。 我想要一些能够让我轻松地从/转换到JSON的东西 这来自于对特定类定义的REST api调用。 我已经找到的解决方案是不够的,或者意味着重写我的 类的代码和添加注释或类似内容。

我想在Java中使用类似GSON的东西来序列化/反序列化类到JSON对象。

结合后来的需要,转换器也可以在JS中运行,我结束了编写自己的包。

它有一些开销。但启动后,添加和编辑非常方便。

初始化模块:

转换模式——允许在字段之间进行映射和确定 如何进行转换 类映射数组 转换函数映射-用于特殊转换。

然后在你的代码中,你像这样使用初始化的模块:

const convertedNewClassesArray : MyClass[] = this.converter.convert<MyClass>(jsonObjArray, 'MyClass');

const convertedNewClass : MyClass = this.converter.convertOneObject<MyClass>(jsonObj, 'MyClass');

或者,转换为JSON:

const jsonObject = this.converter.convertToJson(myClassInstance);

使用这个链接到npm包,以及如何使用模块:json-class-converter的详细说明

还包装了 Angular的用法: angular-json-class-converter

其他回答

将对象原样传递给类构造函数;没有约定或检查

interface iPerson {
   name: string;
   age: number;
}

class Person {
   constructor(private person: iPerson) { }

   toString(): string {
      return this.person.name + ' is ' + this.person.age;
   }  
}


// runs this as // 
const object1 = { name: 'Watson1', age: 64 };
const object2 = { name: 'Watson2' };            // age is missing

const person1 = new Person(object1);
const person2 = new Person(object2 as iPerson); // now matches constructor

console.log(person1.toString())  // Watson1 is 64
console.log(person2.toString())  // Watson2 is undefined

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

而如果你只处理数据,你可以只做一个转换到一个接口(因为它是一个纯粹的编译时结构),这将需要你使用一个TypeScript类,它使用数据实例并对该数据执行操作。

一些复制数据的例子:

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

本质上,你只需要:

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

如果你正在使用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()
})

但遗憾的是,这个方法对嵌套对象不起作用。

如果你需要将json对象转换为typescript类,并在结果对象中使用它的实例方法,你需要使用object。setPrototypeOf,就像我在下面的代码片段中所做的那样:

Object.setPrototypeOf(jsonObject, YourTypescriptClass.prototype)

这是一个简单而又非常好的选择

let person = "{"name":"Sam","Age":"30"}";

const jsonParse: ((key: string, value: any) => any) | undefined = undefined;
let objectConverted = JSON.parse(textValue, jsonParse);

然后你会得到

objectConverted.name