Typescript JSON string to class

前端 未结 4 1746
灰色年华
灰色年华 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.

    0 讨论(0)
  • 2021-01-15 06:09

    One more way to achieve this:

    var data: any = getFromServer();
    var myObjectArray = data as MyObject;
    

    Or:

    var data: any = getFromServer();
    var myObjectArray = <MyObject>dataMyObject;
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 2021-01-15 06:27

    There is a problem when MyObject has 50 or more properties...

    Add a constructor in your MyObject class so that it extends your json object.

    export class MyObject {
        constructor( json: any )
        {
          $.extend(this, json);
        }
        id : number;
        text : string;
    
        methodOnMyObject() {...}
    }
    

    In your ajax callback, create the MyObject object from your json Object:

    let newObject = new MyObject( json );
    newObject.methodOnMyObject();
    

    I detailed the solution in that post.

    0 讨论(0)
提交回复
热议问题