[英]Getting the count (number of items) in a json response in swift
I am on the process of learning swift now. 我正在学习快速的过程。 I have used ANetworking (library in Obj C) in my swift code. 我在快速代码中使用了ANetworking(Obj C中的库)。 I have successfully been able to return the parsed JSON. 我已经能够成功返回解析的JSON。 However I would want to find the count of the json items that are returned. 但是,我想查找返回的json项的计数。 Here is what I did so far: 这是我到目前为止所做的:
//in viewDidAppear function
manager.GET(url,
parameters: nil,
success: { (operation: AFHTTPRequestOperation!, responseObject: AnyObject!) in
self.jsonFunc(responseObject.description)
I did the above like this question in stackoverflow: AFNetworking and Swift - Save json response 我在stackoverflow中做了这样的问题: AFNetworking和Swift-保存json响应
Now, in the function jsonFunc, I am trying to get the count of the json data as so: 现在,在函数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)
}
}
}
}
What is the conversion mistake that I am doing/missing here? 我在这里/错过的转换错误是什么?
By default, AFHTTPRequestOperationManager sets responseSerializer to an AFJSONResponseSerializer instance, so responseObject already is your parsed JSON set as Dictionary. 默认情况下,AFHTTPRequestOperationManager将responseSerializer设置为AFJSONResponseSerializer实例,因此responseObject已经是您设置为Dictionary的已解析JSON。 Here is the code (refactored to remove some redundancy in casting and typing): 这是代码(经过重构以消除转换和键入时的某些冗余):
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)
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.