How to parse a JSON object to a TypeScript Object How to parse a JSON object to a TypeScript Object angular angular

How to parse a JSON object to a TypeScript Object


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 firstlet 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);


The reason that the compiler lets you cast the object returned from JSON.parse to a class is because typescript is based on structural subtyping.
You don't really have an instance of an Employee, you have an object (as you see in the console) which has the same properties.

A simpler example:

class A {    constructor(public str: string, public num: number) {}}function logA(a: A) {    console.log(`A instance with str: "${ a.str }" and num: ${ a.num }`);}let a1 = { str: "string", num: 0, boo: true };let a2 = new A("stirng", 0);logA(a1); // no errorslogA(a2);

(code in playground)

There's no error because a1 satisfies type A because it has all of its properties, and the logA function can be called with no runtime errors even if what it receives isn't an instance of A as long as it has the same properties.

That works great when your classes are simple data objects and have no methods, but once you introduce methods then things tend to break:

class A {    constructor(public str: string, public num: number) { }    multiplyBy(x: number): number {        return this.num * x;    }}// this won't compile:let a1 = { str: "string", num: 0, boo: true } as A; // Error: Type '{ str: string; num: number; boo: boolean; }' cannot be converted to type 'A'// but this will:let a2 = { str: "string", num: 0 } as A;// and then you get a runtime error:a2.multiplyBy(4); // Error: Uncaught TypeError: a2.multiplyBy is not a function

(code in playground)


Edit

This works just fine:

const employeeString = '{"department":"<anystring>","typeOfEmployee":"<anystring>","firstname":"<anystring>","lastname":"<anystring>","birthdate":"<anydate>","maxWorkHours":0,"username":"<anystring>","permissions":"<anystring>","lastUpdate":"<anydate>"}';let employee1 = JSON.parse(employeeString);console.log(employee1);

(code in playground)

If you're trying to use JSON.parse on your object when it's not a string:

let e = {    "department": "<anystring>",    "typeOfEmployee": "<anystring>",    "firstname": "<anystring>",    "lastname": "<anystring>",    "birthdate": "<anydate>",    "maxWorkHours": 3,    "username": "<anystring>",    "permissions": "<anystring>",    "lastUpdate": "<anydate>"}let employee2 = JSON.parse(e);

Then you'll get the error because it's not a string, it's an object, and if you already have it in this form then there's no need to use JSON.parse.

But, as I wrote, if you're going with this way then you won't have an instance of the class, just an object that has the same properties as the class members.

If you want an instance then:

let e = new Employee();Object.assign(e, {    "department": "<anystring>",    "typeOfEmployee": "<anystring>",    "firstname": "<anystring>",    "lastname": "<anystring>",    "birthdate": "<anydate>",    "maxWorkHours": 3,    "username": "<anystring>",    "permissions": "<anystring>",    "lastUpdate": "<anydate>"});


let employee = <Employee>JSON.parse(employeeString);

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