如何将带有嵌套数组的JSON对象映射到TypeScript模型中?

时间:2019-04-17 19:48:09

标签: json angular typescript rxjs angular7

假设我有一个返回以下JSON结构的api:

{
  "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中的pipe和map来实现:

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?

1 个答案:

答案 0 :(得分:2)

如果您的类将不实现任何新功能,则应仅使用接口来强制使用强类型,否则应使用样板。 开始时,您可以像这样派生您的4个接口,并从Typescript安全检查中受益:

names

您调用该API的方法可以这样编写:

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;
}

当您使用数据时(很有可能在订阅块中),您将受益于“智能感知”和强类型输入。

祝你好运!