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

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

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


当前回答

有几种方法可以做到这一点,让我们来看看一些选项:

class Person {
   id: number | undefined;
   firstName: string | undefined;
   //? mark for note not required attribute.
   lastName?: string;
}

// Option 1: Fill any attribute and it would be accepted.
const person1= { firstName: 'Cassio' } as Person ;
console.log(person1);

// Option 2. All attributes must assign data.
const  person2: Person = { id: 1, firstName: 'Cassio', lastName:'Seffrin' };  
console.log(person2);

//  Option 3. Use partial interface if all attribute not required.
const  person3: Partial<Person> = { firstName: 'Cassio' };  
console.log(person3);

//  Option 4. As lastName is optional it will work
const  person4: Person = { id:2, firstName: 'Cassio'  };
console.log(person4);

//  Option 5. Fill any attribute and it would be accepted.
const person5 = <Person> {firstName: 'Cassio'}; 
console.log(person5 );

结果:

[LOG]: {
  "firstName": "Cassio"
} 
[LOG]: {
  "id": 1,
  "firstName": "Cassio",
  "lastName": "Seffrin"
} 
[LOG]: {
  "firstName": "Cassio"
} 
[LOG]: {
  "id": 2,
  "firstName": "Cassio"
} 
[LOG]: {
  "firstName": "Cassio"
} 

如果你有一个接口而不是Typescript类,它也可以工作。

interface PersonInterface {
   id: number;
   firstName: string;
   lastName?: string;
}

播放这个代码

其他回答

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

Object.setPrototypeOf(jsonObject, YourTypescriptClass.prototype)

我在这里使用这个库:https://github.com/pleerock/class-transformer

<script lang="ts">
    import { plainToClass } from 'class-transformer';
</script>

实现:

private async getClassTypeValue() {
  const value = await plainToClass(ProductNewsItem, JSON.parse(response.data));
}

有时必须解析plainToClass的JSON值才能理解它是JSON格式的数据

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

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

一些复制数据的例子:

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

本质上,你只需要:

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

您可以像这样将json转换为属性

class Jobs {
  constructor(JSONdata) {
    this.HEAT = JSONdata.HEAT;    
    this.HEAT_EAF = JSONdata.HEAT_EAF;    
  }
  
}

 var job = new Jobs({HEAT:'123',HEAT_EAF:'456'});

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

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