尝试从Swift 2.0中的json解析数据时出错?

时间:2016-02-28 22:34:51

标签: ios arrays json swift swift2

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

这是我得到的错误

  

无法将'__NSArrayI'(0x10e7eb8b0)类型的值转换为'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()

我收到错误的行是

  

让频道:NSDictionary! = jsonResult!.valueForKey(“CATEGORY_NAME”)   如!的NSDictionary;

1 个答案:

答案 0 :(得分:1)

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

JSON通常作为顶级数组或顶级字典到达。您可以使用NSDictionaryNSArray,甚至是简单的Swift Dictionaries和Arrays。下面的代码将解析顶级字典或数组。您可以将其传递给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]])