Typescript JSON string to class

前端 未结 4 1775
灰色年华
灰色年华 2021-01-15 05:32

Let be this JSON string:

[
    {
        \"id\": 1,
        \"text\": \"Jon Doe\"
    },
    {
        \"id\": 1,
        \"text\": \"Pablo Escobar\"
    }
]         


        
4条回答
  •  轮回少年
    2021-01-15 06:07

    You will need to create a constructor for your class, and call it for each item in the list you receive.

    export class MyObject{
        constructor(public id: number, public text: string) { }
    }
    
    let data = [
      {
        "id": 1,
        "text": "Jon Doe"
      },
      {
        "id": 1,
        "text": "Pablo Escobar"
      }
    ];
    
    let objects = data.map(o => new MyObject(o.id, o.text));
    

    You can check it out in the playground here.

提交回复
热议问题