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

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

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


当前回答

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

其他回答

在后期TS,你可以这样做:

const isMyInterface = (val: any): val is MyInterface => {
  if (!val) { return false; }
  if (!val.myProp) { return false; }
  return true;
};

而用户是这样的:

if (isMyInterface(data)) {
 // now data will be type of MyInterface
}

我也遇到过类似的需求。 我想要一些能够让我轻松地从/转换到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

你可以使用这个npm包。https://www.npmjs.com/package/class-converter

它很容易使用,例如:

class UserModel {
  @property('i')
  id: number;

  @property('n')
  name: string;
}

const userRaw = {
  i: 1234,
  n: 'name',
};

// use toClass to convert plain object to class
const userModel = toClass(userRaw, UserModel);
// you will get a class, just like below one
// const userModel = {
//   id: 1234,
//   name: 'name',
// }

Java爱好者

创建POJO类

export default class TransactionDTO{
    constructor() {
    }
}

按类创建空对象

let dto = new TransactionDto()   // ts object
let json = {name:"Kamal",age:40} // js object

let transaction: TransactionDto = Object.assign(dto,JSON.parse(JSON.stringify(json)));//conversion

目前还没有自动检查从服务器接收到的JSON对象是否具有预期的(读取是否符合)typescript的接口属性。但是你可以使用用户定义的类型保护

考虑以下接口和一个愚蠢的json对象(它可以是任何类型):

interface MyInterface {
    key: string;
 }

const json: object = { "key": "value" }

三种可能的方法:

A.类型断言或放置在变量之后的简单静态强制转换

const myObject: MyInterface = json as MyInterface;

B.简单的静态铸造,前变量和菱形之间

const myObject: MyInterface = <MyInterface>json;

C.高级动态转换,你检查自己的对象结构

function isMyInterface(json: any): json is MyInterface {
    // silly condition to consider json as conform for MyInterface
    return typeof json.key === "string";
}

if (isMyInterface(json)) {
    console.log(json.key)
}
else {
        throw new Error(`Expected MyInterface, got '${json}'.`);
}

你可以玩一下这个例子

注意,这里的困难在于编写isMyInterface函数。我希望TS迟早会添加一个装饰器,将复杂的类型导出到运行时,并让运行时在需要时检查对象的结构。现在,您可以使用json模式验证器,其目的与此大致相同,也可以使用此运行时类型检查函数生成器