代码之家  ›  专栏  ›  技术社区  ›  SP1

以角度将Json映射到对象

  •  0
  • SP1  · 技术社区  · 6 年前

    我有下面的JSON数据

      {
      "columns": [
        {
          "table": "black_list",
          "name": "id",
          "datatype": "uuid"
        },
        {
          "table": "black_list",
          "name": "emailid",
          "datatype": "varchar"
        },
        {
          "table": "black_list",
          "name": "membershipid",
          "datatype": "varchar"
        },
        {
          "table": "black_list",
          "name": "phonenumber",
          "datatype": "varchar"
        }
      ],
      "rows": [
        {
          "id": "59525ac0-9799-11e8-8ea0-897582b5513d",
          "emailid": "bid@email.com",
          "membershipid": "999999",
          "phonenumber": "1234567890"
        }
      ]
    }
    

    我的模型是

    export interface BlacklistData {
        id: string;
        emailid: string;
        membershipid: string;
        phonenumber: string;   
    }
    

    最后,我使用下面的代码从REST API获取结果并试图将其映射到我的对象

    public GetBlackListData(): Observable<WatchlistData[]> {
            var path = "http://ec2compute/BDEServices/RestSearch?selectCls=all&fromCls=demo.black_list";
            return this.http.get(path)
                .pipe(map((result: Response) => this.BlackListData = result.json()));
        }
    

    我只想使用JSON数据的rows部分来映射到我的对象,我不知道如何才能做到这一点。有人能告诉我如何有选择地解析JSON数据并将其映射到我的对象吗。

    我正在使用Angular6并从“rxjs/internal/observate”导入{observate};

    谢谢

    1 回复  |  直到 6 年前
        1
  •  6
  •   Sajeetharan    6 年前

    只需从组件订阅您的服务方法,

    this.yourService.GetBlackListData().subscribe(result => this.result =result.rows);
    

    你的模型应该如下,

        export interface Column {
            table: string;
            name: string;
            datatype: string;
        }
    
        export interface Row {
            id: string;
            emailid: string;
            membershipid: string;
            phonenumber: string;
        }
    
        export interface BlacklistData {
            columns: Column[];
            rows: Row[];
        }