2017-02-15 59 views
1

我的方案是非常簡單的。我試圖在Angular2應用程序中反序列化JSON。問題是在JSON中有一個以@開頭的字段。JSON(場開始@)反序列化在Angular2

例子:

{ 
    "@type": ".StringField", 
    "name": "description", 
    "type": "String", 
    "value": "A" 
    } 

所以我的問題是,我怎麼寫打字稿一類的字段@type?有沒有辦法以一種整潔的方式做到這一點?我找不出解決方案。

@君特Zöchbauer

考慮下面的代碼:

getCustomerProfile(): Observable<CustomerMetaModel> { 
    return this.http.get('/customer/metaModel') 
     .map(this.extractData) 
     .catch(this.handleError); 
    } 

    private extractData(res: Response): string { 
    let body = res.json(); 
    return body || {}; 
    } 

我不自己做解析,但是我讓功能getCustomerProfile()做所有的工作。我如何處理這種情況?

+0

什麼是類屬性必須具有相同的名稱? –

+0

你爲什麼不使用字符串操作代替「@type」從你的json「類型」,並繼續UR業務與新的JSON(字符串你更換後得到) –

+0

@君特Zöchbauer,名稱並不需要是相同的。 – Nano

回答

3
class MyClass { 
    String xtype; 
    String name; 
    String type; 
    String value; 
    constructor(json:any) { 
    this.xtype = json['@type']; 
    this.name = json.name; 
    this.type = json.type; 
    this.value = json.value; 
    } 
} 
var myClass = new MyClass(json); 
+0

我的疑問是,如果你得到一個包含MyClass的數組對象,你必須做一個.MAP以解決陣列?只是問BTW會發生什麼 –

+1

是的,'map()'會這樣做 –

+0

@GünterZöchbauer我在問題中添加了一些其他信息。 – Nano