我有类似的问题,这是我的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) {
}
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) {
}
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!)
}
}