如何在Swift中使用Mappable协议映射自定义对象的域列表

hmi*_*kov 8 json realm swift objectmapper

在我的Realm对象模型中,我有一个名为"Event"的对象.每个事件都有一个EventLocatons列表.我试图从json映射这些对象,但EventLocations列表始终为空.对象看起来像这样(为简洁起见,简化了):

class Event: Object, Mappable {
    override class func primaryKey() -> String? {
        return "id"
    }

    dynamic var id = "" 
    var eventLocations:List<EventLocation> = List<EventLocation>()

    func mapping(map: Map) {
        id <- map["id"]
        eventLocations <- map["eventLocations"]
    }
}

class EventLocation: Object, Mappable {
    override class func primaryKey() -> String? {
        return "id"
    }

    dynamic var id: String = ""
    dynamic var name: String = ""

    required convenience init?(_ map: Map) {
        self.init()
    }

    func mapping(map: Map) {
        id <- map["id"]
        name <- map["name"]
    }
}
Run Code Online (Sandbox Code Playgroud)

我拥有的json是一个Event对象数组.它来自Alamofire响应,我将其映射为:

var events = Mapper<Event>().mapArray(json!)
Run Code Online (Sandbox Code Playgroud)

json看起来像这样:

[
  {
    "id" : "21dedd6d",
    "eventLocations" : [
      {
        "name" : "hh",
        "id" : "e18df48a",
       },
      {
        "name" : "tt",
        "fileId" : "be6116e",
      }
    ]
  },
  {
    "id" : "e694c885",
    "eventLocations" : [
      {
        "name" : "hh",
        "id" : "e18df48a",
       },
      {
        "name" : "tt",
        "fileId" : "be6116e",
      }
    ]
  }
 ]
Run Code Online (Sandbox Code Playgroud)

有谁知道如何使用Mappable协议映射自定义对象列表.Whay是"eventLocations"列表总是空的?

TiM*_*TiM 11

看看ObjectMapper的GitHub仓库中的一个"问题"页面,它看起来并不像Realm List对象那样.

该问题还列出了暂时使其工作的潜在解决方法,我将在此反映:

class MyObject: Object, Mappable {
    let tags = List<Tag>()

    required convenience init?(_ map: Map) { self.init() }

    func mapping(map: Map) {
        var tags: [Tag]?
        tags <- map["tags"]
        if let tags = tags {
            for tag in tags {
                self.tags.append(tag)
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)