gpt4 book ai didi

ios - 尝试在 Swift 2.0 中解析 json 数据时出现错误?

转载 作者:行者123 更新时间:2023-11-29 01:11:36 35 4
gpt4 key购买 nike

我在尝试解析来自 json 的数据时遇到问题。

这是我遇到的错误

Could not cast value of type '__NSArrayI' (0x10e7eb8b0) to 'NSDictionary' (0x10e7ebd60)

            let jsonResult: AnyObject?
do {
jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: [])
print(jsonResult, terminator: "");
let channel: NSDictionary! = jsonResult!.valueForKey("CATEGORY_NAME") as! NSDictionary;
print(channel, terminator: "");
let result: NSNumber! = channel.valueForKey("EVENT_NAME") as! NSNumber;
print(result, terminator: "");

if (result == 0)
{
let alertController = UIAlertController(title: "", message: "There is no live stream right now", preferredStyle: UIAlertControllerStyle.Alert)
alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Default,handler: nil))

self.presentViewController(alertController, animated: true, completion: nil)
}

}
catch
{
// TODO: handle
}

}

task.resume()

我遇到错误的行是

let channel: NSDictionary! = jsonResult!.valueForKey("CATEGORY_NAME") as! NSDictionary;

最佳答案

我同意上面的评论,即您试图强制使用错误的类型(应该避免使用 ! 的原因),但是在不知道您的结构的情况下很难为您提供工作代码数据。

JSON 通常作为顶级数组或顶级字典出现。您可以使用 NSDictionaryNSArray,甚至是普通的 Swift 字典和数组。下面的代码将解析顶级字典或数组。您可以将其传递给 NSJSONSerialization 调用的结果。

func parse (jsonResult: AnyObject?) {

// If our payload is a dictionary
if let dictionary = jsonResult as? NSDictionary {
// Tried to figure out the keys from your question
if let channel = dictionary["CATEGORY_NAME"] as? NSDictionary {
print("Channel is \(channel)")
if let eventName = channel["EVENT_NAME"] as? NSNumber {
print ("Event name is \(eventName)")
}
}

// Same parsing with native Swift Dictionary, assuming the dictionary keys are Strings
if let channel = dictionary["CATEGORY_NAME"] as? [String: AnyObject] {
print("Channel is \(channel)")
if let eventName = channel["EVENT_NAME"] as? NSNumber {
print ("Event name is \(eventName)")
}
}

// Or perhaps our payload is an array?
} else {
if let array = jsonResult as? NSArray {
for element in array {
print(element)
}
}

// Again, same parsing with native Swift Array
if let array = jsonResult as? [AnyObject] {
for element in array {
print(element)
}
}
}
}

parse (["CATEGORY_NAME":["EVENT_NAME" : 22]])
parse (["FOO", "BAR", ["EVENT_NAME" : 22]])

关于ios - 尝试在 Swift 2.0 中解析 json 数据时出现错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35689152/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com