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) { = name;
this.firstName = firstName;
this.lastName = lastName;
this.sessionToken = sessionToken;
And the JSON string as follows,


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