ObjectMapper - 嵌套的动态键

时间:2017-06-28 15:19:22

标签: ios json swift objectmapper

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

我试图用动态密钥映射这个相当复杂的JSON响应,并希望得到一些关于我做错的反馈。

一个小组有关于它的进展情况的统计数据。它的统计数据分为几年甚至几个月。一年内每个月都有结果,投资回报率和胜利。 ROI和win只是百分比,但结果键是用下面的键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类中有stats属性,为nil。

我可以采取哪些其他方法来实现这一目标,或者更改我的实现以完成此任务?

1 个答案:

答案 0 :(得分:2)

<强>解决方案

我通过手动映射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?
}

这个问题可能是一个更好的解决方案,但这是我现在所坚持的。

希望这有帮助!

相关问题