Search code examples
iosswiftobjectmapper

How to map [Color] to [String:Color] using ObjectMapper


I'm trying to map JSON of an Array type to a Dictionary and i'm not quite sure how to do it using ObjectMapper.

Example JSON:

{ 
  "colors": [
   { 
    "id": "red",
    "r": "255",
    "g": "255",
    "b": "255"
   }
  ]
}

Solution

  • You could do the following. Map it to an array first then using the didSet map it to the dictionary.

    class MyClass: Mappable {
        private var arrayColors = [MyClass2] {
        didSet {
                var mapTypes = [String:MyClass2]?
                for obj in arrayColors {
                    mapTypes[obj.id] = obj
                }
    
                types = mapTypes
            }
        }
    
        var colors:[String:MyClass2] = [String:MyClass2]()
    
        func mapping(map: Map) {
            arrayColors <- map["colors"]
        }
    }