Map Json to object in angular

2019-08-31 01:13发布

问题:

I have the below JSON data

  {
  "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"
    }
  ]
}

and my model is

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

and finally I am using the below code to fetch the result from the REST API and trying to map it to my object

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

I only want to use the rows part of the JSON data to map to my object and I am not sure how I can do that. Can someone please tell me how to selectively parse JSON data and map it to my object.

I am using Angular 6 and import { Observable } from 'rxjs/internal/Observable';

Thanks

回答1:

Just subscribe to your service method from your component as,

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

and your Model should be as follows,

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