Reputation: 661
Example: I have a Entity-Class named "Person"
constructor(name:string,surname:string,birthdate:string) {
this.name = name;
this.surname = surname;
this.birthdate = birthdate;
}
And in a "Manager"-Class I get a string that looks like a JSON:
{
"name" : "testName",
"surname" : "testSurrname",
"birthdate" : "JJJJ:MM:DD hh:mm:ss"
}
So how to parse the JSON into a "Person"
personData : Person;
jsonData : JSON;
public toPerson(data: string): Person {
this.jsonData = JSON.parse(data);
.?
.?
.?
personData = new Person(....);
return personData;
}
Upvotes: 4
Views: 23482
Reputation: 37403
public toPerson(data: string): Person {
let jsonData = JSON.parse(data);
personData = new Person(jsonData.name, jsonData.surname, jsonData.birthdate);
return personData;
}
Upvotes: 3
Reputation: 7490
One more elegant solution is to use JSON.parse
reviver:
public static fromJSON(json: any): Person {
if (typeof json === 'string') {
return JSON.parse(json, Person.reviver);
} else if (json !== undefined && json !== null) {
let person = Object.create(Person.prototype);
return Object.assign(person, json);
} else {
return json;
}
}
public static reviver(key: string, value: any): any {
return key === '' ? Person.fromJSON(value) : value;
}
Upvotes: 2