Algobook
- The developer's handbook
mode-switch
back-button
Buy Me A Coffee
Mon May 29 2023

How to create a JSON representation of a TypeScript class and vice versa

In this guide, we will create a JSON representation of our TypeScript class. The JSON will contain all our properties in the class, even nested objects and arrays. Then, we will do the opposite, meaning we will create an instance of our class with a JSON string.

Our class

We will start by creating a Person class that will have some random properties.

interface IWorkHistory { companyName: string; yearsActive: number; } export class Person { public firstName: string; public lastName: string; public age: number; public workHistory: IWorkHistory[]; }

All right, so we have some string values, number and also an array of an object called IWorkHistory.

Let's create our constructor

constructor( firstName: string, lastName: string, age: number, workHistory: IWorkHistory[] ) { this.firstName = firstName; this.lastName = lastName; this.age = age; this.workHistory = workHistory; }

And at last, we will create our toJson function, that will basically run through all the properties and create a new object with the keys and respective values, and then create the JSON with JSON.stringify().

public toJson(): string { const obj: any = {}; Object.getOwnPropertyNames(this).forEach((property) => { obj[property] = this[property as keyof Person]; }); return JSON.stringify(obj); }

Full code

The full Person class should now look like this:

interface IWorkHistory { companyName: string; yearsActive: number; } export class Person { public firstName: string; public lastName: string; public age: number; public workHistory: IWorkHistory[]; constructor( firstName: string, lastName: string, age: number, workHistory: IWorkHistory[] ) { this.firstName = firstName; this.lastName = lastName; this.age = age; this.workHistory = workHistory; } public toJson(): string { const obj: any = {}; Object.getOwnPropertyNames(this).forEach((property) => { obj[property] = this[property as keyof Person]; }); return JSON.stringify(obj); } }

Consume it

And to consume the class, we do as follows:

import { Person } from "./Person"; console.log( new Person("John", "Doe", 55, [ { companyName: "Tesla", yearsActive: 2 }, { companyName: "Apple", yearsActive: 9 }, ]).toJson() );

Output

{ "firstName": "John", "lastName": "Doe", "age": 55, "workHistory": [ { "companyName": "Tesla", "yearsActive": 2 }, { "companyName": "Apple", "yearsActive": 9 } ] }

Factory

Now, we will reverse the action. We will create a Person instance with our JSON basically. Create a class called Factory.ts and add following code:

export class Factory { static create<T>(Type: { new (...args: any): T }, json: string): T { const object = JSON.parse(json); const params = Object.keys(object).map((k) => object[k]); return new Type(...params); } }

So what we are doing here, is creating a function which requires a type of the class and the JSON string basically. Then we will parse the JSON and loop through the keys and assigning them to an array with the parameters which we will then pass in to the constructor of our Type (Person class in our example).

NOTE that the JSON string must have the keys in the same order as the constructor parameters of the class.

Create the Person instance

To create the Person instance, we will take the JSON from the previous part and just pass in to the Factory.create() function.

import { Person } from "./Person"; import Factory from "./Factory"; const json = new Person("John", "Doe", 55, [ { companyName: "Tesla", yearsActive: 2 }, { companyName: "Apple", yearsActive: 9 }, ]).toJson(); const person = Factory.create<Person>(Person, json); console.log(person.firstName); // John console.log(person.lastName); // Doe console.log(person.age); // 55 console.log(person.workHistory); /* [ { companyName: "Tesla", yearsActive: 2 }, { companyName: "Apple", yearsActive: 9 }, ]; */

And there we go!

Outro

In todays guide, we learned how to create a JSON representation of a TypeScript class and then the otherway around where we created an instance of a class using a JSON.

Have you a better solution? Tell me about out here. We love getting feedback of all kinds!

Thanks for reading, and have a great day!

signatureMon May 29 2023
See all our articles