【问题标题】:Casting JSON to complex types将 JSON 转换为复杂类型
【发布时间】:2019-01-08 15:36:54
【问题描述】:

我正在尝试将我的 http.get 响应转换为实际对象 -> 在我的特定情况下是复杂对象数组。

在不需要任何特定转换的正常情况下,您可以执行以下操作(简化):

return this.httpClient.get(api, this._options_get)
  .pipe(
    map((response: any) => {
      return response.value as NewProduct[];
    })
  );

由于我需要将其实际转换为对象,因此我创建了此静态方法:

static toProduct(otherProduct: any): NewProduct {
    let item = new NewProduct();

    Object.keys(otherProduct).forEach(prop => {
        if (typeof otherProduct[prop] === "object" && otherProduct[prop]) {
            if (!item.hasOwnProperty(prop))
                item[prop] = otherProduct[prop];
            Object.assign(item[prop], otherProduct[prop]);
        }
        else
            item[prop] = otherProduct[prop];
    })

    return item;
}

Object.assign 下,我正在获取已在第一行下初始化的现有对象,我只是将otherProduct 中的所有属性复制到它。但是,当涉及到对象数组时,我开始面临问题。示例(带有简化类):

export class Person {
    name:string;
    age:number;
    addresses:Address[] = [];
}
export class Address {
    street:string;
    city:string;
    fullAddress() : string { return this.street + this.city; }
}

一旦有了这种数组,item 中就没有任何初始对象。这意味着没有导致简单Object 的类的初始构造函数。这对 JavaScript 或 TypeScript 来说没有错误;然而,当我试图访问一个类的内部方法时(在我们的简化案例fullAddress() 中,我将无法访问。

我需要它的原因是我在子类上覆盖了toString() 方法,当您使用filter 方法(适用于字符串)时,这对于MatTableDataSource 是必需的。

有没有办法从http.get() 检索元素并将结果正确映射到类型化对象?

【问题讨论】:

    标签: json angular typescript casting jsonserializer


    【解决方案1】:

    你太笼统了。您正在创建对象的对象,而不是具有地址子级的 Product 对象。

    如果您想创建一个新产品,您将必须了解 api 的结果与您想要在 UI 中显示的数据之间的关系。

    因为您使用的是类而不是接口并且想要继承函数,所以将新地址放入新对象的唯一方法是使用 new 关键字。

    而且你必须循环遍历。你不会为此找到捷径。您将需要遍历数据并对其进行转换。如果你的 api 给你一个 ApiPerson 那么你会想要做这样的事情:

    const addresses = apiPerson.addresses.map((apiAddress) => {
        const address = new Address();
        // map properties of apiAddress to address...
        return address;
    });
    

    现在您有了addresses,您可以将apiPerson 映射到new Person() 的属性,然后设置newPerson.addresses = address

    【讨论】:

    • 我希望有更好的方法来管理它。谢谢你的回答
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-29
    相关资源
    最近更新 更多