简体   繁体   中英

pull data from parsed Json with swift

I want to get my CampaignList from JsonObject which I parsed before. But it gives fatal error while it is running.

Error

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

self.CampaignArray = Campaigns as! NSMutableArray  

The code :

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
            }
    }
}

And my response Json is:

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

Try to use SwiftyJSON ( https://github.com/SwiftyJSON/SwiftyJSON )

This library (pod) is very simple and has detailed documentation.

Your example:

I put son file "data.json" in my project and read it. Thank Daniel Sumara for your json example correction.

  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)")
                    }
                }
            }
        }
    }

Also you can use Alamofire-SwiftyJSON ( https://github.com/SwiftyJSON/Alamofire-SwiftyJSON )

PS you have fatal errors because you do not check if value is nil. read about "if let" expression ( https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/OptionalChaining.html )

JSON you provide is invalid. There is lack of , in Campaigns dictionary. Valid JSON looks like:

{
  "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

You receive this error because you try cast nil to NSDictionary object. You have no Campaigns key in JSON you provide, so when you try to get this key from JSON you get nil. In next step you try cast this nil to NSDictionary .

Try use CampaignList key to get data you want.

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)

The same case will be with your Notifications key from JSON Dictionary.

You should also use swift types over objective-c NSDictionary and NSArray.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM