2016-02-28 101 views
0

我有问题试图解析来自JSON的数据。在Swift 2.0中尝试从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() 

线我得到的错误是

let channel:NSDictionary! = jsonResult!.valueForKey(“CATEGORY_NAME”) as! NSDictionary的;

+4

很明显,您的JSON包含一个数组,而不是'CATEGORY_NAME'键的字典。 – rmaddy

回答

1

我同意以上,你试图迫使错误的类型(为什么应该避免!一个原因)的评论,但是很难给你的工作代码,不知道你的数据结构。

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