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

3

我目前使用Swift的ObjectMapper将API返回的JSON对象映射到模型对象中。

我的API返回的JSON格式如下:

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

问题不在于普通映射,而是每个“轨道”的“键”都是其自身的ID... - apps4everyone
2个回答

2

我有一个类似的问题。不幸的是,我还没有找到一种方法可以在不使用索引或硬编码键的情况下选择某些内容。

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

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

2

我有类似的问题,这是我的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 类。
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类的类属性(子对象)而使用

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!)
        }
    }

如果JSON响应中的“data”对象是一个JSON数组,该怎么处理? - Naveen T P

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接