2016-09-30 57 views
1

如何使用ObjectMapper映射子类? 我正在使用swift 2.2和Hyphe,以此为例,但它不使用子类https://bitbucket.org/hyphe/blog-examples/src/59f61b2d8e68c7d3630b40964c4fe3c191d60de6/fetchData/iOS-TechPost1/?at=master 例如,我的API正在拉类的标题和海报,但对于“海报”,我需要它来查找子类, class'src。如何使用ObjectMapper映射子类

我的课'海报'是我的数组“图像”中的一个子类。例如,我在拉JSON是:

"title" : "Election", 
"poster" : { 
    "src" : "https://example.site/image" 
    "alt" : "" 

}

我为班级迅速文件是:

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" 
} 
} 

我已经尝试下面的选项,但他们不工作: 海报< - 地图[ “海报{SRC}”] 海报< - 地图[ “海报”[ “SRC”]]

将不胜感激ÿ我们的帮助!有任何想法吗?

+0

你试过了吗'map [“poster.src”]'? –

回答

2

根据我的理解,您试图使用ObjectMapper将嵌套的json对象映射到Swift对象的属性。 ObjectMapper支持点符号。请查看文档here

在这种情况下,正确的语法是:poster <- map["poster.src"]

+0

非常感谢你! –

+0

它工作的魅力。谢谢。 –

+0

很高兴帮助! @DimitriT –