我想从JsonObject获取我之前解析过的CampaignList。但它在运行时会出现致命错误。
错误
"致命错误:在展开可选值时意外发现nil"
// create wrapper element
this.wrapper = document.createElement("div");
this.wrapper.innerHTML = 'Chars left: <span id="int">' + (this.MAX - input.value.length), '</span>';
// check counter value
var tail = document.getElementById("int");
// Inside the event handler function, the "this" keyword changes meaning to mean the element on which the event listener is attached. Redefining the variable here is one way to get max inside the handler.
var max = this.MAX;
this.INPUT.addEventListener('keyup', function () {
if (max - this.value.length <= 50) {
tail.style.color = "#ffa";
} else if (max - this.value.length <= 0) {
tail.style.color = "#f00";
}
}
代码:
else if (max - this.value.length <= 0)
我的回答Json是:
self.CampaignArray = Campaigns as! NSMutableArray
答案 0 :(得分: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)
P.S。你有致命错误,因为你没有检查值是否为零。阅读“if let”表达式(https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/OptionalChaining.html)