简体   繁体   English

如何将JSON数组从REST API转换为对象

[英]How to convert JSON array from REST API to an object

From my backend I receive message like this: 我从后端收到如下消息:

[
    [
        {
            "id": 1,
            "date": "2018-12-31"
        },
        {
            "id": 12,
            "standard": null,
            "capacity": 7,
            "description": null,
        }
    ],
    [
        {
            "id": 26,
            "date": "2018-12-08"
        },
        {
            "id": 11,
            "standard": null,
            "capacity": 7,
            "description": null,
        }
    ]
]

I want to map this response to list of 2 objects, so I created class: 我想将此响应映射到2个对象的列表,所以我创建了类:

export class Response {

  id: string;
  date: string;
  standard: string;
  capacity: number;
  description: string;
}

I my method, where I calling a service I tried different methods, and even backendData.forEach doesn't work - Angular doesn't recognize backendData as an array. 在我的方法中,我在调用服务时尝试了不同的方法,甚至backendData.forEach也无法正常工作-Angular无法将backendData识别为数组。

getData(){
    this.service.getData().subscribe(backendData=>{
      //how to convert  backendData to an array of Response[]?
    })
  }

I will be very grateful for every help I have been stuck with this for couple of time. 我会很感激我在此期间所遇到的每一次帮助。

Maybe it helps 也许有帮助

getData(){
    this.service.getData().subscribe(backendData=> {
        //how to convert  backendData to an array of Response[]?
        return backendData.map(array => Object.assign(array[0], array[1]))
    })
}

I'm not sure that you really can convert to Response type this array, because your id is string, but in response you got number, also you got nullable description and standard in response 我不确定您是否真的可以将这个数组转换为Response类型,因为您的id是字符串,但是在响应中您得到了数字,在响应中您也得到了可为空的descriptionstandard

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

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