我正在使用Alamofire + AlamofireObjectMapper以及ObjectMapper使用JSON API(Reddit)。我正在努力创建模型,并提出一个不能按预期工作的建议解决方案。我会尽力解释......
我收到的JSON响应有一个基类Thing
,如下所示
class Thing<T where T:Mappable>: Mappable {
var id: String?
var name: String?
var kind: String?
var data: T?
required init?(_ map: Map) {}
func mapping(map: Map) {
id <- map["id"]
name <- map["name"]
kind <- map["kind"]
data <- map["data"]
}
}
data
属性因我提出的请求类型而异。在这种特殊情况下,它应该是Listing
类型,如下所示。
class Listing<T where T: Mappable>: Mappable {
var before: String?
var after: String?
var modhash: String?
var children: [Thing<T>]?
required init?(_ map: Map) {}
func mapping(map: Map) {
before <- map["before"]
after <- map["after"]
modhash <- map["modhash"]
children <- map["children"]
}
}
children
属性是Thing
个对象的数组,但data
为不同的类型,在这种情况下为Post
class Post: Mappable {
var author: String?
var creationDate: Int?
var name: String?
var numberOfComments: Int?
var score: Int?
var text: String?
var stickied: Int?
var subreddit: String?
var title: String?
var url: String?
var preview: Images?
required init?(_ map: Map) {}
func mapping(map: Map) {
author <- map["author"]
creationDate <- map["created_utc"]
name <- map["name"]
numberOfComments <- map["num_comments"]
score <- map["score"]
text <- map["selftext"]
stickied <- map["stickied"]
subreddit <- map["subreddit"]
title <- map["title"]
url <- map["url"]
preview <- map["preview"]
}
}
使用AlamofireObjectMapper扩展,将JSON响应解析为我的自定义模型,我们使用
public func responseObject<T : Mappable>(keyPath: String? = default, completionHandler: Alamofire.Response<T, NSError> -> Void) -> Self
它期待泛型类型。我将使用定义为Response<Thing<Listing<Post>>, NSError>
的类型,如下所示......
RedditAPIService.requestSubReddit(subReddit: nil, withSortType: .Hot, afterPost: nil, postsAlreadyShown: nil).responseObject { (response: Response<Thing<Listing<Post>>, NSError>) -> Void in
if let value = response.result.value {
print(value.kind)
}
}
我看到的问题是Listing
对象上的数据损坏。
我期待children
对象中只有1个值,而不是&gt; 900 Zillion!
我知道我可以将Thing
和Listing
子类化为特定类型,但我也很好奇为什么这不能按预期工作。有任何想法吗?谢谢!