How to parse a JSON object to a TypeScript Object

后端 未结 8 715
谎友^
谎友^ 2020-11-30 05:21

I am currently trying to convert my received JSON Object into a TypeScript class with the same attributes and I cannot get it to work. What am I doing wrong?

8条回答
  •  旧巷少年郎
    2020-11-30 06:01

    If you use a TypeScript interface instead of a class, things are simpler:

    export interface Employee {
        typeOfEmployee_id: number;
        department_id: number;
        permissions_id: number;
        maxWorkHours: number;
        employee_id: number;
        firstname: string;
        lastname: string;
        username: string;
        birthdate: Date;
        lastUpdate: Date;
    }
    
    let jsonObj: any = JSON.parse(employeeString); // string to generic object first
    let employee: Employee = jsonObj;
    

    If you want a class, however, simple casting won't work. For example:

    class Foo {
        name: string;
        public pump() { }
    }
    
    let jsonObj: any = JSON.parse('{ "name":"hello" }');
    let fObj: Foo = jsonObj;
    fObj.pump(); // crash, method is undefined!
    

    For a class, you'll have to write a constructor which accepts a JSON string/object and then iterate through the properties to assign each member manually, like this:

    class Foo {
        name: string;
    
        constructor(jsonStr: string) {
            let jsonObj: any = JSON.parse(jsonStr);
            for (let prop in jsonObj) {
                this[prop] = jsonObj[prop];
            }
        }
    }
    
    let fObj: Foo = new Foo(theJsonString);
    

提交回复
热议问题