如何正确地将数据从API转换为我的类?

时间:2017-10-27 14:50:15

标签: typescript

我目前正在处理一个以字符串形式返回所有内容的API。 这是查询服务器时得到的结果:

{
    "id": "254", // string
    "firstName": "John",
    "isActive": "1" // can be 0 or 1. (bool)
    "venues": [
        { "id": "1", "label": "McNodals" },
        { "id": "2", "label": "Kurger Bing" }
    ]
}

我想将它(转换)转换为:

User {
    id: 254 // as a number
    firstName: "John" // it stays a string
    isActive: true // convert the 1 to bool
    venues: [
        Venue { id: 1, label: "McNodals" },
        Venue { id: 2, label: "Kurger Bing" }
    ]
}

我找到了一种方法来做到这一点,但我不喜欢它,我想知道是否可以用指令做我想要的(动态转换)。

我使用这个有一个方法deserialize的类,它将字符串转换为int和bools

export class Transformer {
    protected toInt = []
    protected toBool = []
    protected toObject = []

    deserialize(instanceData) {
        const keys = Object.keys(this)
        for (const key of keys) {
            if (instanceData.hasOwnProperty(key)) {
                if (this.toInt.indexOf(key) !== -1)
                    this[key] = parseInt(instanceData[key])
                else if (this.toBool.indexOf(key) !== -1)
                    this[key] = parseInt(instanceData[key]) !== 0
                else
                    this[key] = instanceData[key]
            }
        }
    }
}

然后在我的所有课程中,我只需要扩展Transformer并添加反序列化方法

class User extends Transformer {
    public id: number = 0
    public firstName: string = ""
    public isActive: boolean = false
    public venues: Venue[] = []
    protected toInt = ['id']
    protected toBool = ['isActive']

    constructor(instanceData) {
        super()
        this.deserialize(instanceData)
    }

    deserialize(instanceData) {
        let data = instanceData
        super.deserialize(instanceData)
        this.venues = data.venues.map(v => new Venue(v))
    }
}

class Venue extends Transformer {
    public id: number = null
    public label: string
    protected toInt = ['id']

    constructor(instanceData) {
        super()
        this.deserialize(instanceData)
    }

    deserialize(instanceData) {
        super.deserialize(instanceData)
    }
}

我不喜欢到处写toInt和toBool。

有没有其他方法可以使用打字稿来实现这一目标?

谢谢!

0 个答案:

没有答案