从 Typescript 解析 JSON 恢复数据成员但不恢复类型:无法在结果上调用方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17449074/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 02:50:07  来源:igfitidea点击:

Parsing JSON from Typescript restores data members but not type: cannot call methods on result

jsontypescript

提问by MarkusT

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:

当我将对象 p1 的 JSON 字符串化结果解析回另一个对象 p2 时,第二个对象获取与第一个对象关联的数据,但我无法在其上调用任何网络。使用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");

How do I parse the JSON data and get a proper Person object?

如何解析 JSON 数据并获得正确的 Person 对象?

采纳答案by Nahuel Greco

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

回答by Fenton

JSON is a representation of the data only, not any behaviour.

JSON 只是数据的表示,而不是任何行为。

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.

您可以在接受 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());