如何使用TypeScript类对象映射json对象

时间:2018-11-08 11:11:16

标签: typescript angular6

我正在将我的angularjs应用程序转换为angular6,并且我面临将json对象转换为打字稿对象列表的问题。在我的angular6应用程序中,我正在使用this.http.get(Url)从api和我的api响应中获取数据,如下所示

[  
       {  
          "offerId":"be88ffe4-f3be-450a-bf5f-39702f841373",
          "expirationDate":"2018-11-09T00:00:00",
          "priority":1,
          "description":"2 monthly installments of $75.34",
          "totalAmount":150.68,
          "futurePayments":[  
             {  
                "id":"9ab0f191-2acc-4795-808f-5ff4ca01ec68",
                "suggestedPaymentDate":"2018-11-08T00:00:00",
                "minDate":"2018-11-08T00:00:00",
                "maxDate":"2018-11-08T00:00:00",
                "suggestedPaymentAmount":75.34,
                "minPaymentAmount":75.34,
                "maxPaymentAmount":75.34
             },
             {  
                "id":"196399d4-893c-4916-85d3-2c134eb8ad73",
                "suggestedPaymentDate":"2018-12-08T00:00:00",
                "minDate":"2018-11-09T00:00:00",
                "maxDate":"2019-01-07T00:00:00",
                "suggestedPaymentAmount":75.34,
                "minPaymentAmount":75.34,
                "maxPaymentAmount":75.34
             }
          ],
          "isSettlement":true,
          "tier":0,
          "code":null
       },
       {  
          "offerId":"7bb19ed1-246c-458c-ae30-8588de87d3ea",
          "expirationDate":"2018-11-09T00:00:00",
          "priority":2,
          "description":"$50 down and 3 monthly installments",
          "totalAmount":150.68,
          "futurePayments":[  
             {  
                "id":"27db97ff-11bc-4faa-b2fa-83252b334961",
                "suggestedPaymentDate":"2018-11-08T00:00:00",
                "minDate":"2018-11-08T00:00:00",
                "maxDate":"2018-11-08T00:00:00",
                "suggestedPaymentAmount":50.0,
                "minPaymentAmount":50.0,
                "maxPaymentAmount":50.0
             },
             {  
                "id":"5149f20b-1e05-4680-bd5c-afc8c332f0fa",
                "suggestedPaymentDate":"2018-12-08T00:00:00",
                "minDate":"2018-11-09T00:00:00",
                "maxDate":"2019-01-07T00:00:00",
                "suggestedPaymentAmount":50.0,
                "minPaymentAmount":100.0,
                "maxPaymentAmount":20.0
             },
             {  
                "id":"bf268808-4870-49f2-ba97-8df749ed048c",
                "suggestedPaymentDate":"2019-01-08T00:00:00",
                "minDate":"2018-12-09T00:00:00",
                "maxDate":"2019-01-15T00:00:00",
                "suggestedPaymentAmount":50.68,
                "minPaymentAmount":100.0,
                "maxPaymentAmount":20.0
             }
          ],
          "isSettlement":false,
          "tier":0,
          "code":null
       },
       {  
          "offerId":"e266f49b-0640-4797-8c43-04e5284b599d",
          "expirationDate":"2018-11-09T00:00:00",
          "priority":1,
          "description":"Settle right now for $100",
          "totalAmount":100.0,
          "futurePayments":[  
             {  
                "id":"5074a769-aae2-452e-b12a-26422972f8c0",
                "suggestedPaymentDate":"2018-11-08T00:00:00",
                "minDate":"2018-11-08T00:00:00",
                "maxDate":"2018-11-08T00:00:00",
                "suggestedPaymentAmount":100.0,
                "minPaymentAmount":100.0,
                "maxPaymentAmount":100.0
             }
          ],
          "isSettlement":true,
          "tier":1,
          "code":null
       }
    ]

现在我想将此JSON对象转换为Typescript类对象。类结构在下面给出

export class SettlementOffer {

  constructor(offerId: string,
    tier: number,
    priority: number,
    code: string,
    description: string,
    amountNow: number,
    futurePayments: Array<FuturePaymentDto>,
    allowEdit: boolean,
    isSettlement: boolean) {
    this.offerId = offerId;
    this.tier = tier;
    this.priority = priority;
    this.code = code;
    this.description = description;
    this.amountNow = amountNow;
    this.futurePayments = futurePayments;
    this.allowEdit = allowEdit;
    this.isSettlement = isSettlement;
  }

  offerId: string;
  tier: number;
  priority: number;
  code: string;
  description: string;
  amountNow: number;
  futurePayments: Array<FuturePaymentDto>;
  allowEdit: boolean;
  isSettlement: boolean;
}

export class FuturePaymentDto {
  constructor(id: string, suggestedPaymentDate: Date, minDate: Date, maxDate: Date, suggestedPaymentAmount: number, minPaymentAmount: number, maxPaymentAmount: number) {
    this.maxPaymentAmount = maxPaymentAmount;
    this.minPaymentAmount = minPaymentAmount;
    this.suggestedPaymentAmount = suggestedPaymentAmount;
    this.maxDate = moment(maxDate.toISOString().substr(0, 10)).toDate();
    this.minDate = moment(minDate.toISOString().substr(0, 10)).toDate();
    this.suggestedPaymentDate = moment(suggestedPaymentDate.toISOString().substr(0, 10)).toDate();
    this.id = id;
  }

  id: string;
  suggestedPaymentDate: Date;
  minDate: Date;
  maxDate: Date;
  suggestedPaymentAmount: number;
  minPaymentAmount: number;
  maxPaymentAmount: number;
}

我正在使用

,因此我需要的输出是Array<SettlementOffer>
this.http.get('api/debtor/account/${accountId}/offers').subscribe(response => response.json().map(r => new SettlementOffer(r.offerId, r.tier, r.priority, r.code, r.description, r.amountNow, r.futurePayments, r.allowEdit, r.isSettlement)))

我面临的问题是映射json对象。我正在尝试上面的代码,但对我不起作用。我需要别人的帮助...

下面是我执行此操作的旧版本代码

public getOffers(accountId: string): ng.IPromise<Array<SettlementOffer>> {

            return this.$http.get(`/api/debtor/account/${accountId}/offers`)
                .then(data => {

                    return _.map(<any[]>data.data,
                        stuff => {
                            return new SettlementOffer(stuff.offerId,
                                Number(stuff.tier),
                                Number(stuff.priority),
                                stuff.code,
                                stuff.description,
                                Number(stuff.amountNow),
                                _.map(stuff.futurePayments, (data: any) => {
                                    return new FuturePaymentDto(data.id,
                                        new Date(data.suggestedPaymentDate),
                                        new Date(data.minDate),
                                        new Date(data.maxDate),
                                        data.suggestedPaymentAmount,
                                        data.minPaymentAmount,
                                        data.maxPaymentAmount);
                                }),
                                stuff.allowEdit,
                                stuff.isSettlement);
                        });
                });
        }

1 个答案:

答案 0 :(得分:0)

前段时间我也遇到过类似的问题,解决方案是威胁将JSON响应作为接口并将其传递给对象的构造函数:

export interface IJsonResponse {
  field1: string;
  field2: string;
}

export class MyClass implements IJsonResponse {

  field1: string;
  field2: string;

  constructor(iIn: IJsonResponse) {
    this.field1 = iIn.field1;
    this.field2 = iIn.field2;
  }

  mapToJson(): IJsonResponse {
    return {
      field1: this.field1,
      field2: this.field2,
    }
  }
}

这可以确保您满足以下条件:

  • 字段名称在JSON和Class实例中将是相同的
  • 如果你 从您的REST服务中添加/删除某些内容,只需从中添加/删除它即可 界面,TS编译器将自动投诉丢失的字段
  • 通过一些额外的工作,您可以创建其他方法来进行转换 类对象返回接口表单

我对您的代码的建议是避免将多个参数传递给构造函数。只需将对象传递给它,这将节省您的时间,减少出错的可能性,并且如果您希望跳过单个参数,则不会在地球上造成地狱:)