Wednesday, August 8, 2018

How to Convert JSON Object to Interface/class in typescript? and examples

Map JSON to interface tutorials

In this tutorial, 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 calls REST API which calls backend services, 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 follow it.
to map json to the interface, It is not required to do anything from the developer side, Just follow some guidelines to allow the typescript compiler to do the conversion

It is not required to match all fields in JSON object with interfaces,
  • interface fields are a subset of JSON object
  • Interface fields names and type should match with object data
We can do the conversion in two ways
1. Implicit interface conversion
2. Explicit interface conversion

Implicit interface conversion

The developer will not write any code to do the conversion. just follow guidelines as per above, Typescript compiler will do automatically
Example

function getEmployees(): Array  {
    return  [
        { 'id': 1, 'name': 'john', 'salary': 50000 },
        {'id': 2,'name': 'Kiran','salary': 40000}
    ];
}

The interface should be created like as below using interface keyword.
Declared interface with three properties, It is not compulsory to declared 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 list of arrays, Then in your app you should map it to Array of employees or Employee[]


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

Explicit Interface conversion 

In this, Developer will write a code to convert to interface This will be very useful when we need to customize or process some data before converting to interface/classes Using first-class functions - array's method map(), which iterates JSON object array and do map the elements to the interface as seen in below code.

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
}

Nested JSON object interface mapping

In this example, Each employee has address with one to one mapping. In this created two interfaces one for employee and another for address declared mapping address in employe interface using like normal data type declaration.' The same implicit interface mapping rules apply here
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,
}
In the same way, we can also map the custom JSON objects like recursive json types or tree model data each parent contains children. We have seen all the above examples with interfaces, You can also do the map json to classes


EmoticonEmoticon

Note: Only a member of this blog may post a comment.