Typescript JSON string to class

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

提交回复
热议问题