2016-08-15 62 views
0

我想從我之前分析過的JsonObject中獲取CampaignList。但它在運行時會出現致命錯誤。使用swift從分析的Json中提取數據

錯誤

"fatal error: unexpectedly found nil while unwrapping an Optional value"

self.CampaignArray = Campaigns as! NSMutableArray 

代碼:

var CampaignArray:NSMutableArray = [] 

func Get(){ 
    let res: String = "" 

    let jsonObject = ["PhoneNumber": "xxxxx"] 
    let Jsn = JsonClass(value: jsonObject, text: res) 

    Alamofire.request(.POST, "http://MYURL",parameters: jsonObject, 
     encoding: .JSON).validate(statusCode: 200..<303) 
     .validate(contentType: ["application/json"]) 
     .responseJSON { (response) in 
      NSLog("response = \(response)") 

      switch response.result { 
      case .Success: 
       guard let resultValue = response.result.value else { 
        NSLog("Result value in response is nil") 
        //completionHandler(response: nil) 
        return 
       } 
       let responseJSON = resultValue 
       print(responseJSON) 
       let result = Jsn.convertStringToDictionary(responseJSON as! String)! 
       print("result: \(result)") 
       let Campaigns = (result as NSDictionary)["Campaigns"] 
       print(Campaigns) 
       self.CampaignArray = Campaigns as! NSMutableArray 
       let notifications = (result as NSDictionary)["Notifications"] 
       print(notifications) 
       break 
      case .Failure(let error): 
       NSLog("Error result: \(error)") 
       // Here I call a completionHandler I wrote for the failure case 
       return 
      } 
    } 
} 

我的回答JSON是:

json: {"CampaignList":[ 
     {"Bonus":"5","CampaignId":"zQUuB2RImUZlcFwt3MjLIA==","City":"34"} 
      {"Bonus":"3","CampaignId":"VgYWLR6eL2mMemFCPkyocA==","City":"34"}], 
"MemberId":"ZBqVhLv\/c2BtMInW52qNLg==",  
"NotificationList":[{"Notification":"Filiz Makarnadan Milli Piyango Çekiliş Hakkı Kazanmak İster misin ?","PhoneNumber":"555555555"}]} 
+1

你應該停止使用NSMutableArray/NSDictionary/etc並使用Swift數組和字典。 //不要強制展開你的Optionals,總是用可選的綁定處理可能的失敗(如果讓別的)。 //還要注意變量和屬性應該是小寫的,否則其他讀者的代碼會誤導你的對象的類型。 – Moritz

回答

0

嘗試使用SwiftyJSON(https://github.com/SwiftyJSON/SwiftyJSON

這個庫(pod)非常簡單並且有詳細的文檔。

你舉的例子:

我把兒子文件「data.json」在我的項目和閱讀。感謝Daniel Sumara爲您的json示例更正。

if let path = NSBundle.mainBundle().pathForResource("data", ofType: "json") { 
     if let data = NSData(contentsOfFile: path) { 
      let json = JSON(data: data) 

      if let CampaignList = json["CampaignList"].array { 
       for index in 0 ..< CampaignList.count { 

        print("Campaign [\(index)]") 
        if let CampaignId = CampaignList[index]["CampaignId"].string { 
         print("  CampaignId: \(CampaignId)") 
        } 

        if let City = CampaignList[index]["City"].string { 
         print("  City: \(City)") 
        } 

        if let Bonus = CampaignList[index]["Bonus"].string { 
         print("  Bonus: \(Bonus)") 
        } 
       } 
      } 

      if let MemberId = json["MemberId"].string { 
       print("MemberId: \(MemberId)") 
      } 

      if let NotificationList = json["NotificationList"].array { 
       print("NotificationList") 
       for notification in NotificationList { 
        if let Notification = notification["Notification"].string { 
         print("  Notification: \(Notification)") 
        } 

        if let PhoneNumber = notification["PhoneNumber"].string { 
         print("  PhoneNumber: \(PhoneNumber)") 
        } 
       } 
      } 
     } 
    } 

您也可以使用Alamofire-SwiftyJSON(https://github.com/SwiftyJSON/Alamofire-SwiftyJSON

附:你有致命的錯誤,因爲你不檢查價值是否爲零。閱讀「如果讓」表達式(https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/OptionalChaining.html

+0

我不能用swifty json得到任何結果。當我打印出「JSON」時,我可以看到輸出,但是當我嘗試打印廣告系列時,它返回零。 'var json = JSON(data) print(「json:\(json)」) if let campaigns = json [「CampaignList」]。array { print(「campaigns:\(campaigns)」) }' – slytrkmn

+0

你可以在這裏粘貼你的JSON答案嗎? –

+0

那麼,這個解決方案有幫助嗎? –

0

您提供的JSON無效。 Campaigns字典中缺少,。 有效的JSON的樣子:

{ 
    "CampaignList": [ 
    { 
     "Bonus": "5", 
     "CampaignId": "zQUuB2RImUZlcFwt3MjLIA==", 
     "City": "34" 
    }, 
    { 
     "Bonus": "3", 
     "CampaignId": "VgYWLR6eL2mMemFCPkyocA==", 
     "City": "34" 
    } 
    ], 
    "MemberId": "ZBqVhLv/c2BtMInW52qNLg==", 
    "NotificationList": [ 
    { 
     "Notification": "Filiz Makarnadan Milli Piyango Çekiliş Hakkı Kazanmak İster misin ?", 
     "PhoneNumber": "555555555" 
    } 
    ] 
} 

fatal error: unexpectedly found nil while unwrapping an Optional value

您收到此錯誤,因爲你嘗試投零到NSDictionary對象。 您在提供的JSON中沒有Campaigns密鑰,因此當您嘗試從JSON獲取此密鑰時,您將得到零。在下一步中,您嘗試將此零投到NSDictionary

嘗試使用CampaignList鍵來獲得你想要的數據。

let result: [String: AnyObject] = Jsn.convertStringToDictionary(responseJSON as! String)! 
let campaigns: [Campaign] = result["CampaignList"] as! [Campaign] 
print(Campaigns) 
self.CampaignArray = campaigns 
let notifications = result["NotificationList"] 
print(notifications) 

相同的情況將與您的Notifications鍵從JSON Dictionary。

你還應該使用swift類型來覆蓋objective-c NSDictionary和NSArray。