如何将带有嵌套数组的JSON对象映射到typescript模型中?
假设我有一个返回以下JSON结构的api:如何将带有嵌套数组的JSON对象映射到typescript模型中?,json,angular,typescript,rxjs,angular7,Json,Angular,Typescript,Rxjs,Angular7,假设我有一个返回以下JSON结构的api: { "Response": { "status": { "code": "SUCCESS", "message": "owner found", "count": "1" }, "owners": [ { "ownerId": "12345", "name": "Example Person", "cars": [
{
"Response": {
"status": {
"code": "SUCCESS",
"message": "owner found",
"count": "1"
},
"owners": [
{
"ownerId": "12345",
"name": "Example Person",
"cars": [
{
"make": "Toyota"
"year": "2004"
"model": "Camry"
}
]
}
]
}
}
我想将此json结构映射到以下类型脚本模型:
export class ApiResponse{
constructor(
public status: Status,
public owners: Owner[]
) {}
}
export class Status {
constructor(
public code: string,
public message: string,
public count: number
) {}
}
export class Owner{
constructor(
public ownerId: number,
public name: string,
public cars: Car[]
) {}
}
export class Car{
constructor(
public make: string;
public year: string;
public model: string;
)
}
根据我对angular 7的理解,您可以使用rxjs中的管道和贴图来实现这一点:
this.http.get(url).pipe(
map((data: any[]) => data.map((item: any) => new ApiResponse(
new Status(
item.status.code,
item.status.message,
item.status.count),
...
使用它,我可以映射JSON对象,但我不确定如何映射数组和嵌套数组
我应该如何使用嵌套数组映射JSON 如果您的类不实现任何新功能,您应该使用接口来强制执行强类型,否则只是样板。 开始时,您可以像这样派生4个接口,并从Typescript安全检查中获益:
export interface ApiResponse{
status: Status,
owners: Owner[]
}
export interface Status {
code: string,
message: string,
count: number
}
export interface Owner{
ownerId: number,
name: string,
cars: Car[]
}
export interface Car{
make: string;
year: string;
model: string;
}
调用该API的方法可以这样编写:
getStatusAndOwners(url): Observable<ApiResponse> {
return this.http.get(url);
}
getStatusAndOwners(url):可观察{
返回此.http.get(url);
}
当您使用数据时(最有可能在subscribe块中),您将受益于“IntelliSense”和强类型
祝你好运 如果您的模型定义实际上只是属性列表,那么它们在功能上等同于接口。因此,不需要实例化新对象,因为不会得到任何结果——TS对接口和类强制执行类型检查。只需将
可观察的
返回组件进行渲染。感谢您的响应,这可以根据需要工作。需要注意的是,我需要强制转换get函数以适应返回值:this.http.get(url)
True,因为我们期望一个可观察的
。做得好!