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

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

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


当前回答

使用“as”声明:

const data = JSON.parse(response.data) as MyClass;

其他回答

你可以用一个tapi.js! 这是一种轻便的自动装置,可以双向工作。

npm i -D tapi.js

然后你就可以简单地做了

let typedObject = new YourClass().fromJSON(jsonData)

或者用承诺

axios.get(...).as(YourClass).then(typedObject => { ... })

你可以在文档里读到更多。

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

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

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

然后你会得到

objectConverted.name

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

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

我在这里使用这个库: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格式的数据

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

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

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