Alamofire, Objectmapper, Realm: Nested Objects

前端 未结 4 1294
梦谈多话
梦谈多话 2021-01-13 05:16

I\'m using Alamofire, Objectmapper, Realm and everything is working beside one thing: I can\'t map nested objects.

class Voting: Object, Mappable {

    dyna         


        
4条回答
  •  北荒
    北荒 (楼主)
    2021-01-13 06:02

    class ListTransform : TransformType where T:Mappable {
        typealias Object = List
        typealias JSON = [AnyObject]
    
        let mapper = Mapper()
    
        func transformFromJSON(_ value: Any?) -> Object? {
            let results = List()
            if let objects = mapper.mapArray(JSONObject: value) {
                for object in objects {
                    results.append(object)
                }
            }
            return results
        }
    
        func transformToJSON(_ value: Object?) -> JSON? {
            var results = [AnyObject]()
            if let value = value {
                for obj in value {
                    let json = mapper.toJSON(obj)
                    results.append(json as AnyObject)
                }
            }
            return results
        }
    }
    

    Then in your model something like this.

    class Parent: Object, Mappable {
        dynamic var id: Int = 0
        var children = List()
    
        required convenience init?(_ map: Map) {
            self.init()
        }
    
        func mapping(map: Map) {
            id <- map["id"]
            child <- (map["children"], ListTransform())
        }
    }
    

提交回复
热议问题