2016-02-04 79 views
1

我有以下代碼通過API獲取json數據。Swift iOS NSJsonSerialization無提示失敗

 let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in 
     // print("Response: \(response)") 
     // print("DATA: \(data)") 

     if data != nil { 
      do { 


       print(NSString(data: data!, encoding: NSUTF8StringEncoding)) 

       if let jsonResults = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as? NSArray { 
        print("\n\nThe return JSON looks like this: \(jsonResults)\n\n") 
       } 
      } catch { 
       print("\n\nProblem getting JSON back from GET API.\n\n") 
      } 

     } else { 
      print("API Not Available") // data was nil 
     } 

    }) // task 

    task.resume() 

NSString的「打印」顯示我的眼睛看起來像有效的JSON。控制檯顯示此爲:

Optional({"id":15,"user_id":11,"breed_id":593,"gender":"Male","age_years":5,"tally":{"count":1246,"struvite":716,"calcium_oxalate":388,"urate":217,"calcium_phosphate":30,"silica":21,"compound":41},"created_at":"2016-02-04T08:26:14.719-06:00","updated_at":"2016-02-04T08:26:14.719-06:00"}) 

但是,「如果讓jsonResults =」語句也成功執行(沒有印刷jsonResults)和捕捉不執行或者 - 因此它似乎是一個無聲的錯誤。

一個非常類似的調用在API的另一部分工作。唯一的區別在於,在此調用的JSON返回中「理貨」是嵌套的。

任何建議表示讚賞。

+1

您在代碼中粘貼的示例數據是字典,而不是數組。您需要將其轉換爲字典類型,例如如[dzk](http://stackoverflow.com/a/35204049/5836843)建議的[[String:Anyobject]]。 – ishaq

回答

-1

答案是DZK和伊斯哈格的響應的組合。

我取代

if let jsonResults = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as? NSArray 

與:

if let jsonResults = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary 

基本片鑄造它作爲一個字典,而不是陣列。

2

的JSON可能無法正確序列化,因此嘗試更換:

if let jsonResults = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as? NSArray 

有:

if let jsonResults = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! [String: AnyObject] 
1
let jsonResults = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSMutableDictionary 

這個實現是很多整理者,你不必指定他們的數據類型。