如何使用 ObjectMapper 的动态键转换 JSON?

How to Convert JSON with dynamic keys with ObjectMapper?

我目前正在使用 Swift 的 ObjectMapper 将 JSON 对象从 API 映射到模型对象

我的apireturns一个JSON像这样:

{
  "tracks": {
        "1322": {
          "id": 1322,
          "gain": 80
        },
        "1323": {
          "id": 1323,
          "gain": 80
        },
        "1324": {
          "id": 1324,
          "gain": 80
        },
        "1325": {
          "id": 1325,
          "gain": 80
        }
      }
}

我遇到了类似的问题。不幸的是,我还没有找到一种方法来 select 不使用索引或硬编码密钥的东西。

但对于你的情况,你可以这样做:

func mapping(map: Map) {
    id <- map["0.id"]
    gain <- map["0.gain"]
}

我有类似的事情,这是我的 JSON:

{
    "goals": {
        "total": 0,
        "ecpa": 0,
        "data": {
            "575afbdca5a101e3088b2b6554398b0c": {
                "volume": 1,
                "ecpa": 4,
                "coa": "5.00"
            },
            "575afbdca5a101e3088b2b6554398frt": {
                "volume": 3,
                "ecpa": 1,
                "coa": "1.00"
            }

        }
    }
 }

这是实现 Mappable 协议的 StatsGoal class

import ObjectMapper

class StatsGoal: Mappable {
    var total: Double?
    var ecpa: Double?
    var data: [String : StatsGoalData]?

    required init?(_ map: Map) {

    }

    // Mappable
    func mapping(map: Map) {
        total   <- map["total"]
        ecpa    <- map["ecpa"]
        data    <- map["data"]
    }
}

这是实现 Mappable 协议的 StatsGoalData,在 StatsGoal class

中用作 class 属性(子对象)
import ObjectMapper

class StatsGoalData: Mappable {
    var volume: Double?
    var ecpa: Double?
    var coa: Double?

    required init?(_ map: Map) {

    }

    // Mappable
    func mapping(map: Map) {
        volume  <- map["volume"]
        ecpa    <- map["ecpa"]
        coa     <- map["coa"]
    }
}

这就是映射后迭代数据 属性 的方法

    for element in stats {
        let data = element.goals?.data
        for statsGoalData in data! {
            let statsGoalDataElement = statsGoalData.1
                print(statsGoalDataElement.ecpa!)
        }
    }