Search code examples
jsonswiftdynamickey

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

Solution

  • 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"]
    }