Storing JSON data in variables of class any
is common practice, but adding typing to these objects is recommended. One approach is to create a static method called fromJson in model classes to instantiate objects from JSON data. Here's an example:
class User {
public firstname: string;
public lastname: string;
public age: number;
constructor() {
}
public static fromJson(userJson: any): User {
var user = new User();
this.firstname = userJson.firstname;
this.lastname = userJson.lastname;
this.age = userJson.age;
return user;
}
}
If a property in your class is another class, you can also create a fromJson method for that class and include it in the main fromJson method like this:
class User {
public firstname: string;
public lastname: string;
public status: Status;
constructor() {
}
public static fromJson(userJson: any): User {
var user = new User();
this.firstname = userJson.firstname;
this.lastname = userJson.lastname;
this.status = Status.fromJson(userJson.status);
return user;
}
}
I hope this explanation is helpful!