JSON is the standard means of communication between systems, whether it be between front-end and back-end or between microservices.
We generally tend to map this JSON data to TypeScript plain objects or interfaces, but sometimes we may need to map this data to a particular TypeScript class.
We have two methods to achieve this:
Object.assign() methodclass-transformer packageObject.assign() methodThe Object.assign() method creates a new class object from JSON data and a given class.
import * as userData from './user.json';// User classclass User {firstname: string;lastname: string;age: number;//returns fullnamegetFullname() {return this.firstname + " " + this.lastname;}//returns agegetAge() {return this.age;}}//Object.assign method will create a new User class mapping the data userDatalet user1 = (<any>Object).assign(new User(), userData)//printing the full nameconsole.log(user1.getFullname())
In this example:
We import the user data from the user.json file.
We define our User class, which has firstname, lastname, and age as member variables and getFullname(), getAge() as methods.
In line 22, we create a new User class object user1 from userData with the Object.assign() method, in which we pass a User class object new User() and userData as parameters.
Line 25 is the proof that we get data from the User class object user1. Here, we print the full name of the user using the getFullName() method provided by the User class.
class-transformer packageInstall the class-transformer package from your package manager with npm.
npm install class-transformer
import * as userData from './user.json';import { plainToClass } from "class-transformer";// User classclass User {firstname: string;lastname: string;age: number;//returns fullnamegetFullname() {return this.firstname + " " + this.lastname;}//returns agegetAge() {return this.age;}}//plainToClass transforms json data to provided classlet user1 = plainToClass(User, userData);// printing the user1 class objectconsole.log(user1);//priting the full name to consoleconsole.log(user1.getFullname());
In this example, we create the data and user class as explained above. The only difference is that we also create a user1 object.
class-transformer comes with a function called plainToClass, which transforms the user JSON data into the User class object user1.