Typescript JSON string to class

前端 未结 4 1773
灰色年华
灰色年华 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:21

    You don't necessarily need a class here. You can just use an interface

    export interface MyObject{
      id: number;
      text: string;
    }
    

    Then you can just write:

    var myObjArray : MyObject[] =  [
      {
        "id": 1,
        "text": "Jon Doe"
      },
      {
        "id": 1,
        "text": "Pablo Escobar"
      }
    ];
    

    If you data comes from the server, you will probably have it in a variable of type any, and you can just assign it to an array of that type and it will work as expected.

    var data: any = getFromServer();
    var myObjectArray:MyObject[] = data;
    

    In typescript you don't need a class implementing an interface. Any object literal that satisfies the interface contract will do.

    If your data is still in string for you can just use JSON.parse(jsonString) to parse the string to JavaScript objects.

    See playground here

提交回复
热议问题