简体   繁体   English

将 JSON 对象转换为 TypeScript 类实例

[英]Cast JSON object to TypeScript class instance

I have a class which have a method:我有一个类有一个方法:

 export class ItemType {
        id1: string;
        description: string;

        treeItemTypeDescription(): string {
            return this.id1 +  this.description;
        }
 }

I get the data of this class form web service and want to call this method:我从这个类表单web服务中获取数据,想调用这个方法:

itemTypeResource.parents(this.originalPosition).then((parents: app.domain.ItemType[]) => {
      console.log(typeof(parents[0]));
      console.log(parents[0].treeItemTypeDescription());
});

But get the error:但得到错误:

TypeError: parents[0].treeItemTypeDescription is not a function

I think the reason of error the JS-object is not linked with TS-object.我认为错误的原因是 JS-object 没有与 TS-object 相关联。 But I don't know how to fix it.但我不知道如何修复它。

Update:更新:

console.log(Object.getOwnPropertyNames(parents[0])); console.log(Object.getOwnPropertyNames(parents[0]));

gives only fields, but not methods:只提供字段,但不提供方法:

 ["autoincrementedId", "description", "entityType", "excelId", "excelParentId", "id1", "id2", "id3", "id4", "id5", "parentAutoId"]

Update2:更新2:

If I create the object by myself all works fine:如果我自己创建对象一切正常:

  var s = new app.domain.ItemType();
  s.id1 = "1";
  s.description = "some";
  console.log(s.treeItemTypeDescription());

Here is a solution I have found:这是我找到的解决方案:

static fromJSON(json: app.domain.ItemType): app.domain.ItemType {

        var result = new ItemType();

        for (var key in json) {
            if(result.hasOwnProperty(key)) {
                result[key] = json[key]
            }
        }

        return result;
    }

I have created the static method to convert JSON objects to TS objects我已经创建了将 JSON 对象转换为 TS 对象的静态方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM