在swift中获取json响应中的计数(项数)

时间:2015-06-18 00:48:48

标签: ios json swift casting afnetworking

我正在学习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)
           }
        }
     }
 }

我在做什么/在这里失踪的转换错误是什么?

1 个答案:

答案 0 :(得分:0)

默认情况下,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)
                }
            }
        }
    }