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?
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!
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));
```
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
let employee = <Employee>JSON.parse(employeeString);
Remember: Strong typings is compile time only since javascript doesn't support it.
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);
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);