How to cast a JSON object inside of the TypeScript class
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:
- Use the
Object.assign()method - Use the
class-transformerpackage
Using the Object.assign() method
The Object.assign() method creates a new class object from JSON data and a given class.
Code
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())
Explanation
In this example:
-
We import the
userdata from theuser.jsonfile. -
We define our User class, which has
firstname,lastname, andageas member variables andgetFullname(),getAge()as methods. -
In line
22, we create a newUserclass objectuser1fromuserDatawith theObject.assign()method, in which we pass aUserclass objectnew User()anduserDataas parameters. -
Line
25is the proof that we get data from theUserclass objectuser1. Here, we print the full name of the user using thegetFullName()method provided by theUserclass.
Using the class-transformer package
Pre-requisite
Install the class-transformer package from your package manager with npm.
npm install class-transformer
Code
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());
Explanation
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.