Javascript Angular2 - 将 JSON 解析为对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42653895/
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-08-23 01:19:43 来源:igfitidea点击:
Angular2 - Parse JSON into an Object
提问by ALSTRA
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:
在“Manager”类中,我得到一个看起来像 JSON 的字符串:
{
"name" : "testName",
"surname" : "testSurrname",
"birthdate" : "JJJJ:MM:DD hh:mm:ss"
}
So how to parse the JSON into a "Person"
那么如何将 JSON 解析为“人”
personData : Person;
jsonData : JSON;
public toPerson(data: string): Person {
this.jsonData = JSON.parse(data);
.?
.?
.?
personData = new Person(....);
return personData;
}
采纳答案by Bougarfaoui El houcine
public toPerson(data: string): Person {
let jsonData = JSON.parse(data);
personData = new Person(jsonData.name, jsonData.surname, jsonData.birthdate);
return personData;
}
回答by Serginho
One more elegant solution is to use JSON.parsereviver:
一种更优雅的解决方案是使用JSON.parsereviver:
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;
}

