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.

It is not required to match all fields in a JSON object with interfaces, But

  • Interface fields are a subset of the JSON object
  • Interface fields names and types should match with object data

We have two ways of converting.

  • Implicit interface conversion
  • Explicit interface conversion

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 },
  ];
}

Here is the sequence of steps to follow

  • 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?

In this example,

  • 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.