Reputation: 33
I'm currently using ObjectMapper for Swift for mapping JSON Object from API to model Object
My api returns a JSON like this:
{
"tracks": {
"1322": {
"id": 1322,
"gain": 80
},
"1323": {
"id": 1323,
"gain": 80
},
"1324": {
"id": 1324,
"gain": 80
},
"1325": {
"id": 1325,
"gain": 80
}
}
}
Upvotes: 3
Views: 2606
Reputation: 562
I had similar thing, this is my JSON:
{
"goals": {
"total": 0,
"ecpa": 0,
"data": {
"575afbdca5a101e3088b2b6554398b0c": {
"volume": 1,
"ecpa": 4,
"coa": "5.00"
},
"575afbdca5a101e3088b2b6554398frt": {
"volume": 3,
"ecpa": 1,
"coa": "1.00"
}
}
}
}
This is StatsGoal class that implements Mappable protocol
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"]
}
}
And this is StatsGoalData that implements Mappable protocol and is used as class property (child object) in StatsGoal 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"]
}
}
and this is how you can iterate over data property after mapping
for element in stats {
let data = element.goals?.data
for statsGoalData in data! {
let statsGoalDataElement = statsGoalData.1
print(statsGoalDataElement.ecpa!)
}
}
Upvotes: 2
Reputation: 374
I'm having a similar problem. Unfortunately I haven't found a way to select something without either using indexes or a hard coded key.
But for your case, you might be able to do this:
func mapping(map: Map) {
id <- map["0.id"]
gain <- map["0.gain"]
}
Upvotes: 2