当我将对象p1的JSON字符串化结果解析回另一个对象p2时,第二个对象获取与第一个对象关联的数据,但我无法在其上调用任何nethods.使用http://www.typescriptlang.org/Playground/我尝试了以下内容:
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");
Run Code Online (Sandbox Code Playgroud)
如何解析JSON数据并获取正确的Person对象?
Fen*_*ton 17
JSON只是数据的表示,而不是任何行为.
您可以在接受JSON对象的对象上创建一个方法并从中保存数据,但JSON对象不能仅传输纯数据的行为(方法等).
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());
Run Code Online (Sandbox Code Playgroud)
尝试这个:
// 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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16333 次 |
| 最近记录: |