ObjectMapper - 嵌套动态键

ObjectMapper - nested dynamic keys

我在 Swift 3.1 中写作,使用 ObjectMapper 将我的 JSON 响应映射到我的模型。

我正在尝试用动态键映射这个相当复杂的 JSON 响应,并希望得到一些关于我做错了什么的反馈。

一个组有关于它的进度的统计信息。它的统计数据细分为数年和数月。一年中的每个月都有结果、投资回报率和胜利。投资回报率和获胜只是百分比,但结果键是用下面的键固定的,1-5,然后是一些整数作为值。

我的JSON

"stats": {
    "2017": {
        "1": {
            "results": {
                "1": 13,
                "2": 3,
                "3": 1,
                "4": 1,
                "5": 0
            },
            "roi": 0.40337966202464975,
            "win": 0.8181818181818182
        },
        "2": {
            "results": {
                "1": 13,
                "2": 5,
                "3": 1,
                "4": 2,
                "5": 1
            },
            "roi": 0.26852551067922953,
            "win": 0.717948717948718
        }
    }
}

我的模特

class GroupResponse: Mappable {
    var stats: [String: [String: StatsMonthResponse]]?

    func mapping(map: Map) {
        stats   <- map["stats"]
    }
}

class StatsMonthResponse: Mappable {
    var tips: [String: Int]?
    var roi: Double?
    var win: Double?

    func mapping(map: Map) {
        tips    <- map["results"]
        roi     <- map["roi"]
        win     <- map["win"]
    }
}

我得到的

我得到的回复在我的 GroupResponse class 中有统计数据 属性,为零。

我还可以采取什么其他方法来完成此任务,或者更改我的实现来完成此任务?

解决方案

我通过手动映射 JSON 解决了我的问题。

class GroupResponse: Mappable {

    var stats: [String: StatsYear]?

    func mapping(map: Map) {
        stats   <- map["stats"]
    }
 }

class StatsYear: Mappable {

    var months: [String: StatsMonth] = [:]

    override func mapping(map: Map) {

        for (monthKey, monthValue) in map.JSON as! [String: [String: Any]] {

            let month = StatsMonth()

            for (monthKeyType, valueKeyType) in monthValue {

                if monthKeyType == "results" {
                    let tipResultDict = valueKeyType as! [String: Int]

                    for (result, tipsForResult) in tipResultDict {
                        month.tips[result] = tipsForResult
                    }
                }
                else if monthKeyType == "roi" {
                    month.roi = valueKeyType as? Double
                }
                else if monthKeyType == "win" {
                    month.win = valueKeyType as? Double
                }
            }
            months[monthKey] = month
        }
    }
}

class StatsMonth {

    var tips: [String: Int] = [:]
    var roi: Double?
    var win: Double?
}

这个问题可能有更好的解决方案,但这是我目前坚持的方法。

希望这对您有所帮助!