【发布时间】:2017-04-05 10:29:32
【问题描述】:
我正在尝试将收到的 JSON 数据映射到我创建的模型上。问题是,JSON 数据有嵌套数组。所以不可能用我想要的方式映射我的数据。我的方式有错误还是有更好的方法来映射我的 JSON 数据?
JSON-数据
{
"data": {
"apiName": "test-application",
"stages": [
{
"stage": "prod",
"id": "xxxxxxxx",
"methods": [
{
"id": "xxxxxx",
"path": "/users/create",
"httpMethods": [
"GET"
],
"methodName": "testMethod",
"url": "https://xxxx/xxxxx/xxxxxx"
}
]
},
{
"stage": "dev",
"id": "xxxxxxx",
"methods": [
{
"id": "xxxxxxx",
"path": "/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 || {};
}
【问题讨论】:
-
您是如何生成 C# 模型的?对我来说看起来不对..在这里复制粘贴您的 json 并与您的比较:json2csharp.com
-
这不是 C#,它是 TypeScript
-
我的错误,但在我看来仍然是错误的,请参见此处:json2ts.com您遇到了什么错误?
-
区别只是,我使用类而不是接口