我现在正在学习 swift。我在我的 swift 代码中使用了 ANetworking (Obj C 中的库)。我已经成功返回解析后的 JSON。但是我想找到返回的 json 项目的数量。这是我到目前为止所做的:
//in viewDidAppear function
manager.GET(url,
parameters: nil,
success: { (operation: AFHTTPRequestOperation!, responseObject: AnyObject!) in
self.jsonFunc(responseObject.description)
我按照 stackoverflow 中的这个问题做了上述操作:AFNetworking and Swift - Save json response
现在,在函数 jsonFunc 中,我尝试获取 json 数据的计数,如下所示:
func jsonFunc(data: AnyObject) {
let count: Int? = data.count // I understand that data is AnyObject. How to typecast and get the number of data items here?
if let ct = count {
println(ct)
for index in 0...ct-1 {
if let parsedData = data[index] as? [String: AnyObject] {
println(parsedData)
}
}
}
}
我在这里做/错过的转换错误是什么?
最佳答案
默认情况下,AFHTTPRequestOperationManager 将responseSerializer 设置为AFJSONResponseSerializer 实例,因此responseObject 已经是您解析的JSON 设置为Dictionary。这是代码(重构以消除强制转换和输入中的一些冗余):
func jsonLoaded(responseObject: AnyObject) {
if let data = responseObject as? NSDictionary {
let count = data.count
print(count)
for index in 0..<count {
//data -- urls for the apps that the user has (for the current logged in user)
if let parsedData = data[index] as? [String: AnyObject] {
print(parsedData)
}
}
}
}
关于ios - 快速获取 json 响应中的计数(项目数),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30904789/