如何使用 ObjectMapper 映射子类? 我正在使用 swift 2.2 和 Hyphe,以此为例,但它不使用子类 https://bitbucket.org/hyphe/blog-examples/src/59f61b2d8e68c7d3630b40964c4fe3c191d60de6/fetchData/iOS-TechPost1/?at=master 例如,我的 API 正在提取类“title”和“poster”,但是对于“poster”,我需要它来找到子类“src”。
我的类“海报”是我的数组“图像”中的一个子类。例如,我正在拉入的 Json 是:
"title" : "Election",
"poster" : {
"src" : "https://example.site/image"
"alt" : ""
我的类(class) swift 文件是:
import Foundation
import RealmSwift
import ObjectMapper
import Foundation
import RealmSwift
import ObjectMapper
protocol Meta {
static func url() -> String
}
class Specimen: Object, Mappable, Meta {
dynamic var title = ""
dynamic var poster = ""
}
//Impl. of Mappable protocol
required convenience init?(_ map: Map) {
self.init()
}
func mapping(map: Map) {
title <- map["title"]
poster <- map["poster"]
}
//Impl. of Meta protocol
static func url() -> String {
return "https://example.site/data"
}
}
我已经尝试了以下选项,但它们不起作用: 海报<- map [“海报{src}”] 海报<- map ["海报"["src"]]
感谢您的帮助!有任何想法吗?
最佳答案
据我了解,您正在尝试使用 ObjectMapper 将嵌套的 json 对象映射到 Swift 对象的属性。 ObjectMapper 为此支持点符号。请查看文档 here .
在这种情况下,正确的语法是:poster <- map["poster.src"]
.
关于swift - 如何使用 ObjectMapper 映射子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39786342/