{

How to Convert JSON Object to Interface or class in typescript?


Typescript JSON Object to Interface or class example 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 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 type 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 guidelines as per above and the Typescript compiler will do 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 as 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 Employee Object. if JSON object is a list of arrays, Then in your app you should map it to Array of employees or Employee[]

Here is an interface declared in Employee.ts.

interface Employee {
    id: number,
    name: string,
    salary: number
}

Explicit Interface conversion

In this, The developer will write a 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 - array’s method map(), that 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 Nested JSON object to interface in typescript?

In this example,

  • Each employee has 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.

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.