How to parse a JSON object to a TypeScript Object

后端 未结 8 654
谎友^
谎友^ 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 05:54

    i like to use a littly tiny library called class-transformer.

    it can handle nested-objects, map strings to date-objects and handle different json-property-names a lot more.

    Maybe worth a look.

    import { Type, plainToClass, Expose } from "class-transformer";
    import 'reflect-metadata';
    
    export class Employee{
        @Expose({ name: "uid" })
        id: number;
    
        firstname: string;
        lastname: string;
        birthdate: Date;
        maxWorkHours: number;
        department: string;
    
        @Type(() => Permission)
        permissions: Permission[] = [];
        typeOfEmployee: string;
        note: string;
    
        @Type(() => Date)
        lastUpdate: Date;
    }
    
    export class Permission {
      type : string;
    }
    
    let json:string = {
        "uid": 123,
        "department": "",
        "typeOfEmployee": "",
        "firstname": "",
        "lastname": "",
        "birthdate": "",
        "maxWorkHours": 1,
        "username": "",
        "permissions": [
          {'type' : 'read'},
          {'type' : 'write'}
        ],
        "lastUpdate": "2020-05-08"
    }
    
    console.log(plainToClass(Employee, json));
    
    ```
    
    

提交回复
热议问题