How to parse a JSON object to a TypeScript Object

后端 未结 8 655
谎友^
谎友^ 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:52

    First of all you need to be sure that all attributes of that comes from the service are named the same in your class. Then you can parse the object and after that assign it to your new variable, something like this:

    const parsedJSON = JSON.parse(serverResponse);
    const employeeObj: Employee = parsedJSON as Employee;
    

    Try that!

    0 讨论(0)
  • 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": "<anystring>",
        "typeOfEmployee": "<anystring>",
        "firstname": "<anystring>",
        "lastname": "<anystring>",
        "birthdate": "<anydate>",
        "maxWorkHours": 1,
        "username": "<anystring>",
        "permissions": [
          {'type' : 'read'},
          {'type' : 'write'}
        ],
        "lastUpdate": "2020-05-08"
    }
    
    console.log(plainToClass(Employee, json));
    
    ```
    
    
    0 讨论(0)
  • 2020-11-30 05:55
    if it is coming from server as object you can do 
    

    this.service.subscribe(data:any) keep any type on data it will solve the issue

    0 讨论(0)
  • 2020-11-30 06:00
    let employee = <Employee>JSON.parse(employeeString);
    

    Remember: Strong typings is compile time only since javascript doesn't support it.

    0 讨论(0)
  • 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 = <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 = <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);
    
    0 讨论(0)
  • 2020-11-30 06:03

    Try to use constructor procedure in your class.

    Object.assign

    is a key

    Please take a look on this sample:

    class Employee{
        firstname: string;
        lastname: string;
        birthdate: Date;
        maxWorkHours: number;
        department: string;
        permissions: string;
        typeOfEmployee: string;
        note: string;
        lastUpdate: Date;
    
        constructor(original: Object) { 
            Object.assign(this, original);
        }
    }
    
    let e = new Employee({
        "department": "<anystring>",
        "typeOfEmployee": "<anystring>",
        "firstname": "<anystring>",
        "lastname": "<anystring>",
        "birthdate": "<anydate>",
        "maxWorkHours": 3,
        "username": "<anystring>",
        "permissions": "<anystring>",
        "lastUpdate": "<anydate>"
    });
    console.log(e);
    
    0 讨论(0)
提交回复
热议问题