【问题标题】:How do I map a JSON object with nested arrays into a typescript model?如何将带有嵌套数组的 JSON 对象映射到打字稿模型中?
【发布时间】:2019-09-08 03:20:06
【问题描述】:

假设我有一个返回以下 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?

【问题讨论】:

  • 如果您的模型定义实际上只是属性列表,那么它们在功能上等同于接口。因此,没有必要实例化新对象,因为没有任何收获——TS 强制对接口和类进行类型检查。只需将Observable 返回给组件进行渲染。

标签: json angular typescript rxjs angular7


【解决方案1】:

如果你的类不会实现任何新功能,你应该使用接口来强制执行强类型,否则只是样板。 开始时,您可以像这样派生 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);
}

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

祝你好运!

【讨论】:

  • 感谢您的回复,这可以根据需要进行。需要注意的是,我需要转换 get 函数以适应返回值:this.http.get&lt;ApiResponse&gt;(url);
  • 是的,因为我们期望Observable&lt;ApiResponse&gt;。干得好!
猜你喜欢
  • 2021-07-06
  • 1970-01-01
  • 2018-06-18
  • 1970-01-01
  • 2017-04-19
  • 2020-08-06
  • 2023-03-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多