简体   繁体   English

Typescript:将JSON对象转换为类/接口对象

[英]Typescript: Convert JSON object to a class/interface object

I m trying to convert an API response to typescript class/interface. 我试图将API响应转换为typescript类/接口。

Here the API returns a list of objects with some properties, but I need only few of the properties of the response object. 这里API返回一个具有一些属性的对象列表,但我只需要几个响应对象的属性。

API Response Example: API响应示例:

[{
    'Id' : 1,
    'Name': 'test',
    'Description: 'Test',
    'PropertyX': 'x',
    'PropertyY' : 'y'
    },
    ...]

Typescript Class 打字稿类

Class Response {
     Id: string;
     Name: string;
    }

Can you please suggest me what will be the best approach for converting the JSON object to a typescript object. 能否请您建议将JSON对象转换为打字稿对象的最佳方法。

I would suggest creating an interface that describes the properties you are using in your app and ignore the rest: 我建议创建一个界面来描述您在应用中使用的属性,并忽略其余的:

So assuming your response looks like: 所以假设您的回答如下:

const response = [{
      'Id' : 1,
      'Name': 'test',
      'Description: 'Test',
      'PropertyX': 'x',
      'PropertyY' : 'y'
    }, {
      'Id' : 2,
      'Name': 'test2',
      'Description: 'Test2',
      'PropertyX': 'x2',
      'PropertyY' : 'y2'
    }
];

and you are only interested in Id and Name , just create an interface like so: 而你只对IdName感兴趣,只需创建一个这样的界面:

interface IMyObject {
  Id: String;
  Name: String;
}

then in the rest of your app you can cast the response to IMyObject[] 然后在你的应用程序的其余部分,您可以将响应转换为IMyObject[]

For example if a function uses your response: 例如,如果函数使用您的响应:

function myFunction(response: IMyObject[]) { ... }

or if you need to return that type, you can do a direct cast like so: 或者如果您需要返回该类型,您可以像这样进行直接投射:

return response as MyObject[];

EDIT: As mentioned in the comment below, simply casting your object to IMyObject does not remove the extra properties you are not interested in. 编辑:如下面的评论所述,只是将您的对象转换为IMyObject不会删除您不感兴趣的额外属性。

To do so, use .map : 为此,请使用.map

const formattedResponse: IMyObject = reponse.map(item => {
  Id: item.Id,
  Name: item.Name
});

You can use forEach method and create a new object with the properties you require. 您可以使用forEach方法并使用所需的属性创建新对象。

myarray=[];
 ngOnInit() {
     this.myvalues();

  }


    myMethod()
        {
           const response = [{
            'Id' : 1,
            'Name': 'test',
            'Description': 'Test',
            'PropertyX': 'x',
            'PropertyY' : 'y'
          }, {
            'Id' : 2,
            'Name': 'test2',
            'Description': 'Test2',
            'PropertyX': 'x2',
            'PropertyY' : 'y2'
          }
        ];

        response.forEach(value=>{
         this.myarray.push(
               {
                'ID':value.Id,
               'Name':value.Name
              }
            )
        });
        console.log(this.myarray);

WORKING DEMO 工作演示

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

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