Angular2 - 将JSON解析为Object

时间:2017-03-07 16:54:17

标签: javascript json angular typescript

示例:我有一个名为" Person"

的实体类
constructor(name:string,surname:string,birthdate:string) {
    this.name = name;
    this.surname = surname;
    this.birthdate = birthdate;
}

在" Manager" -Class中我得到一个看起来像JSON的字符串:

{
    "name" : "testName",
    "surname" : "testSurrname",
    "birthdate" : "JJJJ:MM:DD hh:mm:ss"
}

那么如何将JSON解析为" Person"

personData : Person;
jsonData : JSON;
public toPerson(data: string): Person {
    this.jsonData = JSON.parse(data);
    .?
    .?
    .?
    personData = new Person(....);
    return personData;
}

2 个答案:

答案 0 :(得分:3)

public toPerson(data: string): Person {
    let jsonData = JSON.parse(data);

    personData = new Person(jsonData.name, jsonData.surname, jsonData.birthdate);
    return personData;
}

答案 1 :(得分:2)

一个更优雅的解决方案是使用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;
}