- Cast a JSON Object to a Class in TypeScript
- Use Object.assign to Cast From JSON to Class in TypeScript
- Use Custom Methods to Cast a JSON String to Class in TypeScript
- Casting a JSON object to a TypeScript class
- How to Convert JSON Object to Interface or class in typescript?
- How to Convert json to Object or interface in typescript?
- Implicit interface conversion
- Typescript Explicit Interface conversion
- How to map a Nested JSON object to interface in typescript?
- Summary
Cast a JSON Object to a Class in TypeScript
- Use Object.assign to Cast From JSON to Class in TypeScript
- Use Custom Methods to Cast a JSON String to Class in TypeScript
The data on the internet flows in the form of strings and can be converted to a very popular format called JSON. This JSON representation of the data often represents an object or even a class in TypeScript.
TypeScript provides the functionality to cast an object to a class. This article will discuss how to transform the received object into a TypeScript class to make type support, IDE completions, and other features accessible.
Use Object.assign to Cast From JSON to Class in TypeScript
The Object.assign method gives an easy way of converting JSON objects to a TypeScript class so that the methods associated with the class also become accessible.
The following code segment shows how a JSON object can be cast to a TypeScript class using the Object.assign method.
class Animal name : string; legs : number; eyes : number; constructor(name? : string, legs? : number, eyes? : number) this.name = name ?? 'Default name'; this.legs = legs ?? 0; this.eyes = eyes ?? 0; > getName() return this.name; > getEyes() return this.eyes; > > var jsonString : string = ` "name" : "Tiger", "legs" : 4, "eyes" : 2 >` var animalObj = new Animal(); console.log(animalObj.getEyes()); Object.assign(animalObj, JSON.parse(jsonString)); console.log(animalObj.getEyes());
In the above example, the getEyes() method returned 0 , which was the default value, and when the parsed JSON object was assigned to the animalObj object, it returned 2 , the value in the JSON string.
Use Custom Methods to Cast a JSON String to Class in TypeScript
One can have custom methods such as fromJSON to cast a JSON object to the respective class in TypeScript. This method is more useful as it gives more power to the user.
class Animal name : string; legs : number; eyes: number; constructor(name : string, legs : number, eyes: number) this.name = name; this.legs = legs; this.eyes = eyes; > getName() return this.name; > toObject() return name : this.name, legs : this.legs.toString(), eyes : this.eyes.toString() > > serialize() return JSON.stringify(this.toObject()); > static fromJSON(serialized : string) : Animal const animal : ReturnTypeAnimal["toObject"]> = JSON.parse(serialized); return new Animal( animal.name, animal.legs, animal.eyes ) > > var jsonString : string = ` "name" : "Tiger", "legs" : 4, "eyes" : 2 >` var animalObj : Animal = Animal.fromJSON(jsonString); console.log(animalObj) // this will work now console.log(animalObj.getName());
Animal: "name": "Tiger", "legs": 4, "eyes": 2 > "Tiger"
Shuvayan is a professional software developer with an avid interest in all kinds of technology and programming languages. He loves all kinds of problem solving and writing about his experiences.
Casting a JSON object to a TypeScript class
TL;DR — Use class-transformer to transform JSON object to class instance.
I started working with TypeScript about two years ago. Most of the time I read a JSON object from a remote REST server. This JSON object has all the properties of a TypeScript class. There is a question always buzz my head: How do I cast/parse the received JSON object to an instance of a corresponding class?.
Over time, I found this class-transformer library is super helpful. You can install this into your project and start using it from now on to see the difference. They supported nested property too so you don’t have to worry about that.
It is worth mentioning that not all the time we need to cast from JSON object to a class, but sometimes it is really helpful. As per the example above, If I don’t have the method getFullName in the instance of class, I could create a new util method that takes a plain User object as argument and return the expected result. In my projects, many times I used visitor pattern for handling different concrete classes, and it is required the instance of each class to be working. It won’t work for a plain object. The decision is yours. Put all properties and methods inside a single class is the encapsulation in Object-Oriented Programming (OOP) while Functional Programming treated everything as a function.
The below section was quoted from their readme.
In JavaScript there are two types of objects:
Plain objects are objects that are instances of Object class. Sometimes they are called literal objects, when created via <> notation. E.g var obj = <> Class objects are instances of classes with their own defined constructor, properties, and methods. Usually, you define them via class notation.
Sometimes you want to transform plain javascript object to the ES6 classes you have. For example, if you are loading a JSON from your backend, some API, or a JSON file. After you JSON.parse , it gives you a plain JavaScript object, not an instance of a class you have.
For example you have a list of users that you received from the server:
[ "id": 1, "firstName": "Johny", "lastName": "Cage", "age": 27 >, "id": 2, "firstName": "Ismoil", "lastName": "Somoni", "age": 50 >, "id": 3, "firstName": "Luke", "lastName": "Dacascos", "age": 12 > ]
And you have a User class defined on client side:
export class User id: number firstName: string lastName: string age: number getFullName() return this.firstName + ' ' + this.lastName > isAdult() return this.age > 36 && this.age 60 > >
You are assuming that you are downloading users of type User from users.json file and may want to write following code:
fetch('/api/users').then((users: User[]) => // you can use users here, and type hinting also will be available to you, // but users are not actually instances of User class // this means that you can't use methods of User class >)
In this code you can use users[0].id , you can also use users[0].firstName and users[0].lastName . However you cannot use users[0].getFullName() or users[0].isAdult() because “users” actually is array of plain javascript objects, not instances of User object. You lied to the compiler when you said that its users: User[] .
So what to do? How to make a users array of instances of User objects instead of plain javascript objects? The solution is to create new instances of User object and manually copy all properties to new objects. But things may go wrong very fast once you have a more complex object hierarchy.
Alternatives? Yes, you can use class-transformer. The purpose of this library is to help you to map you plain javascript objects to the instances of classes you have.
This library also great for models exposed in your APIs, because it provides a great tooling to control what your models are exposing in your API. Here is example how it will look like:
fetch('/api/users').then((users: Object[]) => const realUsers = plainToClass(User, users) // now each user in realUsers is instance of User class >)
Now you can use users[0].getFullName() and users[0].isAdult() methods.
This is the result as my console.log in the example does. You could clearly see the type of the object
Working with nested objects
When you are trying to transform objects that have nested objects, its required to know what type of object you are trying to transform. Since Typescript does not have good reflection abilities yet, we should implicitly specify what type of object each property contains. This is done using @Type decorator.
Let’s say we have an album with photos. And we are trying to convert album plain object to class object:
import Type, plainToClass > from 'class-transformer' export class Album id: number name: string @Type(() => Photo) photos: Photo[] > export class Photo id: number filename: string > let album = plainToClass(Album, albumJson) // now album is Album object with Photo objects inside
How to Convert JSON Object to Interface or class in typescript?
This post talks about different ways of converting json to interface in typescript.
During development, data comes from the REST API in the format of JSON format, So you need to write a code to convert the JSON to interface or class in typescript.
We are going to learn various ways of converting JSON objects to Interface/class. In my previous article, Learned how to declared and implement typescript interfaces.
This conversion is required to know as Front applications coded in typescript and calls REST API that interns call backend services, and returns the response in JSON format.
This JSON object needs to transfer to the interface/class to bind this data to UI.
Interfaces have no implementation but it has some rules, where classes or objects that implement this interface should follow it.
How to Convert json to Object or interface in typescript?
To convert JSON to the interface, the developer does not need to do anything. simply write code that follows some rules to allow the typescript compiler to do the conversion. First, the Interface is defined with properties the same as JSON fields.
- Interface fields are a subset of the JSON object
- Interface fields names and types should match with object data
Implicit interface conversion
The developer will not write any code to do the conversion. just follow the guidelines above and the Typescript compiler will do it automatically
Here is an example using the Implicit conversion approach
The function returns Employee data.
function getEmployees(): Array return [ id: 1, name: "john", salary: 50000 >, id: 2, name: "Kiran", salary: 40000 >, ]; >
- The interface should be created like the below using the interface keyword.
- Declared interface with three properties, It is not compulsory to declare all properties.
- You can declare two fields also as per your requirement, but properties names should match with the name of JSON object keys
- Each JSON object represents an Employee Object. if the JSON object is a list of arrays, Then in your app you should map it to an Array of employees or Employee []
Here is an interface declared in Employee.ts .
interface Employee id: number; name: string; salary: number; >
Typescript Explicit Interface conversion
In this, The developer will write code to convert to the interface.
It is useful when customizing or processing data before converting it to interfaces or classes.
Using first-class functions — the array’s method map() , iterates through the JSON object array and maps the elements to the interface , as shown in the code below.
const emps = [ 'id': 1, 'name': 'john', 'salary': 50000 >, 'id': 2,'name': 'Kiran','salary': 40000> ]; const empsClass: Employee = emps.map(obj => id: obj.Id, name: obj.Name >); interface Employee id: number, name: string, salary: number >
How to map a Nested JSON object to interface in typescript?
- Each employee has an address with one-to-one mapping.
- Created two interfaces one for employee and another for address
- declared mapping address in employee interface using like normal data type declaration.’
- The same implicit interface mapping rules apply here to declare the address interface.
const emps = [ 'id': 1, 'name': 'john', 'salary': 50000, "address": "colony": "John Road", "state": "NewYork", "country":"USA" >>, 'id': 2,'name': 'Kiran','salary': 40000 "address": "colony": "Stree 12", "state": "NewYork", "country":"USA" >> ]; interface Employee id: number, name: string, salary: number, address:Address > interface Address colony: string, state: string, country:string, >
Custom JSON objects, such as recursive JSON types or tree model data, are used in this approach. Each parent contains children.
We have seen all the above examples with interfaces. You can also do the map JSON to classes.
Summary
To summarize, Learned multiple ways to convert JSON to object or interface were discussed. You can select one approach based on your needs.