简体   繁体   中英

Getting an error when trying to parse data from a json in Swift 2.0?

I'm having issues trying to parse data from a json.

This is the error I'm getting

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()

The line I'm getting the error on is

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

I agree with the comment above that you're trying to force the wrong type (a reason why ! should be avoided), but it's hard to give you working code without knowing the structure of your data.

JSON typically arrives as a top level array or a top level dictionary. You can use NSDictionary and NSArray , or even plain Swift Dictionaries and Arrays. The code below will parse either a top level dictionary or array. You would pass it your the result of your NSJSONSerialization call.

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]])

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