2017-02-15 63 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