Search code examples
iosjsonswiftobjectmapper

ObjectMapper how map Dictionary of [String:CustomObject] With Index as CustomObject Property


I started to use ObjectMapper this week and I'm trying to map a JSON into 2 CustomClasses but I don't known if ObjectMapper has some function to do what I want. First CustomClass has a property of type: [String:CustomClass2] where the index of this Dictionary should be property ID of second CustomObject.

JSON Used:

{ 
  "types": [
   { 
    "id": "mk8QPMSo2xvtSoP0cBUD",
    "name": "type 1",
    "img": "type_1",
    "showCategories": false,
    "modalityHint": [
      "K7VqeFkRQNXoh2OBxgIf"
    ],
    "categories": [
      "mP3MqbJrO5Da1dVAPRvk",
      "SlNezp2m3PECnTyqQMUV"
    ]
   }
  ]
}

Classes Used:

class MyClass: Mappable {
    var types:[String:MyClass2] = [String:MyClass2]() //Index should be ID property of MyClass2 Object
    required init?(map:Map) {
        guard map.JSON["types"] != nil else {
            return nil
        }
    }
    func mapping(map: Map) {
        types <- map["types"]
    }
}
class MyClass2: Mappable {
    private var id: String!
    private var name: String!
    private var img: String!
    private var showCategories: Bool!
    private var modalityHint: [String]?
    private var categories: [String]?
    required init?(map: Map) { }
    func mapping(map: Map) {
        id <- map["id"]
        name <- map["name"]
        img <- map["img"]
        showCategories <- map["showCategories"]
        modalityHint <- map["modalityHint"]
        categories <- map["categories"]
}

Solution

  • In your JSON the types key is an array not a Dictionary.

    Change:

    var types:[String:MyClass2] = [String:MyClass2]()
    

    To:

    var types:[Class2] = []
    

    Like this:

    class MyClass: Mappable {
        private var arrayTypes = [MyClass2] {
            didSet{
                var mapTypes = [String:MyClass2]?
                for obj in arrayTypes {
                    mapTypes[obj.id] = obj
                }
    
                types = mapTypes
            }
        }
    
        var types:[String:MyClass2] = [String:MyClass2]()
        required init?(map:Map) {
            guard map.JSON["types"] != nil else {
                return nil
            }
        }
        func mapping(map: Map) {
            arrayTypes <- map["types"]
        }
    }