我正在通过alamofire提出请求,并将此作为回复:
{
success: true,
data: [
{
_id: "5615dd59e4b0d2d408b385ff",
name: "Exam Prep",
info: "Tools designed to increase students' performance on standardized tests",
active: true
},
{
_id: "5615dd75e4b0d2d408b38603",
name: "Mathematics",
info: "The study of topics such as quantity numbers, structure, space, and change",
active: true
},
{
_id: "5615dd8de4b0d2d408b38604",
name: "Science",
info: "Knowledge in the form of predictions about the universe",
active: true
},
{
_id: "5615dda5e4b0d2d408b38605",
name: "Language Arts",
info: "The study of languages, composition, and grammar",
active: true
}
]
}
使用通用对象序列化作为模板形式Alamofire的文档:http://cocoadocs.org/docsets/Alamofire/2.0.2/我的主题类有以下方法:
static func collection(response response: NSHTTPURLResponse, representation: AnyObject) -> [Subject] {
var subjects: [Subject] = []
if let representation = representation as? [[String: AnyObject]] {
for subjectRepresentation in representation {
if let subject = Subject(response: response, representation: subjectRepresentation) {
subjects.append(subject)
}
}
}
return subjects
}
然而,if let representation =表示为什么? [[String:AnyObject]]总是失败。我认为这与json数据在"数据"中有关。而不是根级对象,但我不知道如何告诉演员拔出"数据"要生成Subject类的实例的元素。帮助
答案 0 :(得分:2)
您可以使用data
提取valueForKeyPath
元素:
static func collection(response response: NSHTTPURLResponse, representation: AnyObject) -> [Subject] {
var subjects: [Subject] = []
if let representation = representation.valueForKeyPath("data") as? [[String: AnyObject]] {
for subjectRepresentation in representation {
if let subject = Subject(response: response, representation: subjectRepresentation) {
subjects.append(subject)
}
}
}
return subjects
}
答案 1 :(得分:0)
将representation
投射为[String: AnyObject]
let representation = representation as? [String: AnyObject]