2017-04-05 91 views
1

我正试图在我创建的模型上映射接收到的JSON数据。问题是,JSON数据嵌套数组。所以不可能用我想要的方式来映射我的数据。我的方式有错误还是有更好的方法来映射我的JSON数据?嵌套的JSON数组到模型的Angular2映射

JSON-数据

{ 
"data": { 
    "apiName": "test-application", 
    "stages": [ 
     { 
      "stage": "prod", 
      "id": "xxxxxxxx", 
      "methods": [ 
       { 
        "id": "xxxxxx", 
        "path": "https://stackoverflow.com/users/create", 
        "httpMethods": [ 
         "GET" 
        ], 
        "methodName": "testMethod", 
        "url": "https://xxxx/xxxxx/xxxxxx" 
       } 
      ] 
     }, 
     { 
      "stage": "dev", 
      "id": "xxxxxxx", 
      "methods": [ 
       { 
        "id": "xxxxxxx", 
        "path": "https://stackoverflow.com/users/create", 
        "httpMethods": [ 
         "GET" 
        ], 
        "methodName": "testMethod", 
        "url": "https://xxxxx/xxxxxx/xxxx" 
       } 
      ] 
     } 
    ] 
} 
} 

型号:

import {ApiStage} from "./ApiStage"; 
export class Api { 
    constructor(values: Object = {}){ 
    Object.assign(this, values); 
    } 
    public apiName: string; 
    public stages: ApiStage[]; 
} 

import {ApiMethod} from "./ApiMethod"; 
export class ApiStage { 
    constructor(values: Object = {}){ 
    Object.assign(this, values); 
    } 
    public stage: string; 
    public id: string; 
    public methods: ApiMethod[]; 
} 

export class ApiMethod { 
    constructor(values: Object = {}){ 
    Object.assign(this, values); 
    } 
    public id: string; 
    public path: string; 
    public httpMethods: string[]; 
    public methodName: string; 
    public url: string; 
} 

HTTP的方法在服务:

getApi() { 
return this.http.post(this.url, this.data, {headers: this.headers}) 
    .map(this.extractData) 
    .map(api => new Api(api)) 
    .catch((error: any) => Observable.of(error.json().error || 'Server error')); 
} 

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

您是如何生成C#模型的?看起来不对我..复制粘贴你的JSON在这里,并与你的比较:http://json2csharp.com/ –

+0

这不是C#,它的TypeScript – bobafett1

+0

我的错误,但仍然看起来不对我,看到这里:http:// json2ts.com/你有什么错误? –

回答

1

JSON具有只是一组非常有限的数据类型 - 字符串,数字,布尔值,数组,对象。如果要将JSON对象树转换为自定义类的对象树,则需要递归执行并创建正确的对象 - 而不是使用看起来像您的类的对象。

这个过程可能很乏味且容易出错,所以最好使用一个库,比如Class变换器(https://github.com/pleerock/class-transformer),它可以为你做到。您只需使用装饰器(例如@Type(...))注释类,然后使用plainToClass()方法转换纯JSON对象,或使用classToPlain()将实对象序列化为JSON。