繁体   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