在数组中存储获取的json词典,结果为nil

时间:2015-10-03 00:53:37

标签: ios json

我有一个包含url,title和timestamp等属性的文件数据库。当我加载某个视图控制器时,我正在获取文件数据并将其加载到tableview中。因为有多个文件,每个文件都有3个属性,我试图将数据保存在数组中,然后遍历数组中的每个对象并提取JSON数据。截至目前,GET请求和响应都是成功的,但数组仍为零。我的做法错了吗?

 let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in

        guard let data = data, response = response else
        {
            print("No data or response!")
            return
        }

        let strData = NSString(data: data, encoding: NSUTF8StringEncoding)
        print("Body: \(strData)", terminator: "")

        do {
            self.fetchedArray = try NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves) as? NSArray


            print("fetched array count is %i \(self.fetchedArray!.count)")


            if let jsonArray: NSArray = self.fetchedArray{


                for var i = 0; i<jsonArray.count; ++i {


                    let dictResult = jsonArray.objectAtIndex(i) as! NSDictionary

                    let recording = Recordings()
                    recording.trackURL = dictResult["url"] as? String
                    recording.trackTimestamp = dictResult["timestamp"] as? String
                    recording.trackAuthor = dictResult["author"] as? String
                    recording.trackTitle = dictResult["title"] as? String
                    self.recordings?.addObject(recording)

                    }
            }
            else
            {
                // No error thrown, but not NSDictionary
                let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)
                print("No error thrown but could not parse JSON: '\(jsonStr)'")
            }
        }
        catch let parseError {
            // Log the error thrown by `JSONObjectWithData`
            print(parseError)
            let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)
            print("Error thrown. could not parse JSON: '\(jsonStr)'")
        }
    })

    task.resume()

现在它执行倒数第二个语句print("No error thrown but could not parse JSON: '\(jsonStr)'")并打印出所有数据。

序列化前的数据记录:

Response: <NSHTTPURLResponse: 0x7c349990> { URL: http://127.0.0.1:5000/auth/serve_current_user_files } { status code: 200, headers {
"Content-Length" = 239;
"Content-Type" = "application/json";
Date = "Sat, 03 Oct 2015 02:53:00 GMT";
Server = "Werkzeug/0.10.4 Python/2.7.10";
"Set-Cookie" = "session=eyJfZnJlc2giOnRydWUsIl9pZCI6eyIgYiI6Ik16RXhaRGs0TldVM1lUQmxNREJrWlRNeFpqZ3pZMkl3T1dRNE5EZzVPREk9In0sInVzZXJfaWQiOiIxIn0.CPDUjA.Mm56VPuZPIokCZVoRw7X2ySz960; HttpOnly; Path=/";
} }Body: Optional({
  "recordings": [
  {
  "author": 1, 
  "timestamp": "Sun, 27 Sep 2015 17:44:54 GMT", 
  "title": "Test1.m4a", 
  "url": "/Users/allahesharghi/Desktop/Omid/pythonprojects/sound/sound/uploads/omid1/Test1.m4a"
}
]

1 个答案:

答案 0 :(得分:0)

你的JSON是:

{
    "recordings": [
        {
            "author": 1,
            "timestamp": "Sun, 27 Sep 2015 17:44:54 GMT",
            "title": "Test1.m4a",
            "url": "/Users/allahesharghi/Desktop/Omid/pythonprojects/sound/sound/uploads/omid1/Test1.m4a"
        }
    ]
}

因此,根对象不是数组,它是一个字典,其中包含键recordings的字典数组。这意味着当你说

self.fetchedArray = try NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves) as? NSArray

self.fetchedArray将为零,因为向NSArray的向下转换将失败,因为NSDictionary无法向下转换为NSArray。

您需要访问根词典,然后从录制密钥访问该阵列 -

do {
       someDictionary = try NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves) as? NSDictionary
       self.fetchedArray = someDictionary!["results"] as? NSArray
            print("fetched array count is %i \(self.fetchedArray!.count)")
...