When I parse the JSON-stringified result of an object p1 back into another object p2, the second object gets the data associated with the first object, but I cannot call any nethods on it. Using http://www.typescriptlang.org/Playground/ I tried the following:
class Person
{
constructor(public name: string, public age: number) {
}
Age() { return this.age; }
}
// Create a person
var p: Person = new Person("One", 1);
// Create a second person from the JSON representation
// of the first (NOTE: assert it is of type Person!)
var p2: Person = <Person>JSON.parse(JSON.stringify(p));
document.writeln("Start");
document.writeln(p.name); // OK: One
document.writeln(p.Age()); // OK: 1
document.writeln(p2.name); // OK: One
document.writeln(p2.age; // OK: 1
document.writeln(p2.Age()); // ERROR: no method Age() on Object
document.writeln("End");
How do I parse the JSON data and get a proper Person object?
Use the JSON. parse() method to parse a JSON string in TypeScript, e.g. const result: Person = JSON. parse(jsonStr) . The method parses a JSON string and returns the corresponding value.
parse() The JSON. parse() method parses a JSON string, constructing the JavaScript value or object described by the string. An optional reviver function can be provided to perform a transformation on the resulting object before it is returned.
To parse a JSON object to a TypeScript object, we use the JSON. parse method. interface Employee { departmentId: number; permissionsId: number; maxWorkHours: number; employeeId: number; firstName: string; lastName: string; } const jsonObj: any = JSON.
Introduction to TypeScript JSON type. The TypeScript comes up with the functionality of working with JSON Type data. JSON being the JavaScript Object Notation, is used to make a data model that is easy to write and read. We can easily analyze large and complex data set with this TypeScript JSON type.
JSON is a representation of the data only, not any behaviour.
You could create a method on the object that accepts the JSON object and hydrates the data from it, but a JSON object cannot transfer the behaviour (methods etc) only the plain data.
class Person
{
constructor(public name: string, public age: number) {
}
Age() { return this.age; }
static fromJson(json: string) {
var data = JSON.parse(json);
return new Person(data.name, data.age);
}
}
var p: Person = new Person("One", 53);
var jsonPerson = JSON.stringify(p);
var p2: Person = Person.fromJson(jsonPerson);
alert(p2.Age().toString());
try this:
// Create a person
var p: Person = new Person("One", 1);
// JSON roundtrip
var p_fromjson = JSON.parse(JSON.stringify(p))
// Hydrate it
var p2: Person = Object.create(Person.prototype);
Object.assign(p2, p_fromjson);
document.writeln(p2.Age()); // OK
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With