4

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;
}
2
  • Where is this string coming from and why is it broken JSON? Assuming you can sort that out, the best approach is to rewrite your constructor so it looks like constructor(data) { Object.assign(this, data); }, then invoke it with new Person(this.jsondata). Commented Mar 7, 2017 at 16:57
  • sorry, i wrote the json wrong Commented Mar 7, 2017 at 17:06

2 Answers 2

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

    personData = new Person(jsonData.name, jsonData.surname, jsonData.birthdate);
    return personData;
}
Sign up to request clarification or add additional context in comments.

7 Comments

at this.jsonData. i can only choose between this.jsonData.stringify and this.jsonData.parse...
the data is already stringified why you want to use stringify ?
could you join the chat, it would be faster :) chat.stackoverflow.com/rooms/137472/…
this. on each of the parameters to new Person is unnecessary, it should just be jsonData.*
thnx @ssube I forgot the this cuz I updated the code many times :)
|
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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.