簡體   English   中英

快速從解析的Json中提取數據

[英]pull data from parsed Json with swift

我想從之前解析過的JsonObject獲取我的CampaignList。 但是它在運行時會產生致命錯誤。

錯誤

“致命錯誤:解開可選值時意外發現nil”

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: {"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"}]}

嘗試使用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

PS,您有致命錯誤,因為您不檢查值是否為nil。 閱讀有關“ if let”表達式的信息( https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/OptionalChaining.html

您提供的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"
    }
  ]
}

致命錯誤:解開Optional值時意外發現nil

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

嘗試使用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)

JSON字典中的Notifications鍵也是如此。

您還應該在Objective-C NSDictionary和NSArray上使用快速類型。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM