我正在使用Alamofire,Objectmapper,Realm,一切都在一件事:我无法映射嵌套对象.
class Voting: Object,Mappable { dynamic var votingID: String = "" dynamic var question: String = "" var votingOptions = List<VotingOption>() required convenience init?(_ map: Map) { self.init() } func mapping(map: Map) { votingID <- map["id"] question <- map["question"] votingOptions <- map["votingOptions"] } override class func primaryKey() -> String { return "votingID" } } class VotingOption: Object,Mappable{ dynamic var optionID: String = "" dynamic var text: String = "" required convenience init?(_ map: Map) { self.init() } func mapping(map: Map) { optionID <- map["id"] text <- map["optionText"] } override class func primaryKey() -> String { return "optionID" } }
我想要映射的JSON是:
{ "Voting": [ { "question": "Which option do yo prefer?","id": "7f073efd-6f3d-43f2-9fe4-5cad683b77a2","votingOptions": [ { "optionText": "Option 3","id": "3bc0a618-8791-4862-a7fd-5f2df464697d" },{ "optionText": "Option 1","id": "84c6a830-814b-40c8-a252-c074be5d689a" },{ "optionText": "Option 2","id": "8872ef6f-fc70-445a-802e-d39944006467" } ] } ] }
解决方法
旧的ListTransform解决方案不再适用于Swift 3.
这就是我现在正在使用的;例如,将它放在名为ListExtensions.swift的文件中.
import Foundation import ObjectMapper import RealmSwift /// Maps object of Realm's List type func <- <T: Mappable>(left: List<T>,right: Map) { var array: [T]? if right.mappingType == .toJSON { array = Array(left) } array <- right if right.mappingType == .fromJSON { if let theArray = array { left.append(objectsIn: theArray) } } }
这允许您像这样简单地使用它:
class Parent: Object,Mappable { dynamic var id: Int = 0 var children = List<Child>() required convenience init?(_ map: Map) { self.init() } func mapping(map: Map) { id <- map["id"] children <- map["children"] } }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。