Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Convert JSON with dynamic keys with ObjectMapper?

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
        }
      }
}
like image 879
apps4everyone Avatar asked Apr 27 '26 22:04

apps4everyone


2 Answers

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"]
}
like image 77
Grantism Avatar answered Apr 30 '26 12:04

Grantism


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!)
        }
    }
like image 31
DoubleK Avatar answered Apr 30 '26 12:04

DoubleK



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!