Monday, September 24, 2018

Parse JSON string in Typescript

Typescript is typed superset of Javascript. It has extension of .ts, it finally gets compiled to plain Java Script.

Here we will see how we can parse a string representing JSON data and map it to TypeScript Object.

Say the following is our UserDetails object
export class UserDetails {
name: string;
firstName: string;
lastName: string;
sessionToken: string;
roles: Array<string>;
constructor(name?: string, firstName?:string, lastName?:string, sessionToken?: string) {
this.name = name;
this.firstName = firstName;
this.lastName = lastName;
this.sessionToken = sessionToken;
}
And the JSON string as follows,

{
"name":"Sidd",
"firstName":"Sidd",
"lastName":"Bhatt",
"sessionToken":"d501dce2-a628-4e4c-9ea0-1b2ea31f5270",
"rememberMe":false,
"authenticated":true
}

Following code will parse the above string and create instance of UserDetails object.
let currentUserStr = "contains the above sample json string;
let userDetailsObject:UserDetails = JSON.parse(currentUserStr);
console.log("Session Token = " + userDetailsObject.sessionToken);

No comments :

Post a Comment