Angular2 - Parse JSON into an Object

23,126

Solution 1

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

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

Solution 2

One more elegant solution is to use 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;
}
Share:
23,126
ALSTRA
Author by

ALSTRA

Updated on August 01, 2022

Comments

  • ALSTRA
    ALSTRA almost 2 years

    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:

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

    So how to parse the JSON into a "Person"

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