swift – Alamofire,Objectmapper,Realm:嵌套对象

swift – Alamofire,Objectmapper,Realm:嵌套对象,第1张

概述我正在使用Alamofire,Objectmapper,Realm,一切都在一件事:我无法映射嵌套对象. class Voting: Object, Mappable { dynamic var votingID: String = "" dynamic var question: String = "" var votingOptions = List<VotingOp 我正在使用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"                }            ]        }    ]}

VotingOption中的映射功能永远不会被调用.

解决方法 旧的Listtransform解决方案不再适用于Swift 3.

这就是我现在正在使用的;例如,将它放在名为ListExtensions.swift的文件中.

import Foundationimport ObjectMapperimport RealmSwift/// Maps object of Realm's List typefunc <- <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"]    }}
总结

以上是内存溢出为你收集整理的swift – Alamofire,Objectmapper,Realm:嵌套对象全部内容,希望文章能够帮你解决swift – Alamofire,Objectmapper,Realm:嵌套对象所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1009611.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-22
下一篇 2022-05-22

发表评论

登录后才能评论

评论列表(0条)

保存