2017-03-07 176 views
2

例子:我有一個實體 - 類名爲「Person」Angular2 - 解析JSON爲對象

constructor(name:string,surname:string,birthdate:string) { 
     this.name = name; 
     this.surname = surname; 
     this.birthdate = birthdate; 
    } 

而在一個「經理」一流的我得到一個字符串,它看起來像一個JSON:

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

那麼如何將JSON解析成一個 「人」

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

這個字符串來自哪裏,爲什麼它被打破JSON?假設你可以對此進行分類,最好的方法是重寫你的構造函數,使其看起來像'constructor(data){Object.assign(this,data); }',然後用'new Person(this.jsondata)'調用它。 – 2017-03-07 16:57:21

+0

對不起,我寫了json錯誤 – ALSTRA

回答

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

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

對不起,我寫了json錯誤 – ALSTRA

+0

@ALSTRA在this.jsonData處看到更新 –

+0

。我只能選擇this.jsonData.stringify和this.jsonData.parse ... – ALSTRA

1

一個更優雅的解決方案是使用JSON解析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; 
    }