2015-04-19 50 views
3

我有一個json對象,我需要序列化成一個字典。我知道我可以將它序列化爲NSDictionary,但自從NSJSONSerialization into swift dictionary

「在Swift 1.2中,具有本機Swift等價物(NSString,NSArray,NSDictionary等)的Objective-C類不再自動橋接。

文獻:[http://www.raywenderlich.com/95181/whats-new-in-swift-1-2]

我寧願它在本土迅速字典,以避免尷尬橋接。

我不能使用NSJSONSerialization方法,因爲它只映射到NSDictionay。將JSON串行化成快速字典的另一種方法是什麼?

+0

'讓nsDict = NSJSONSerialzation.whatever();讓swiftDict:[String:AnyObject] = nsDict as [String:AnyObject];' –

回答

4

您可以直接使用Swift詞典和NSJSONSerialization

{"id": 42}例子:

let str = "{\"id\": 42}" 
let data = str.dataUsingEncoding(NSUTF8StringEncoding) 

let json = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers, error: nil) as! [String:Int] 

println(json["id"]!) // prints 42 

或者與AnyObject

let json = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers, error: nil) as! [String:AnyObject] 

if let number = json["id"] as? Int { 
    println(number) // prints 42 
} 

Playground screenshot

UPDATE:

如果您的數據可能是n金正日,你必須使用安全展開,以避免發生錯誤:

let str = "{\"id\": 42}" 
if let data = str.dataUsingEncoding(NSUTF8StringEncoding) { 
    // With value as Int 
    if let json = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as? [String:Int] { 
     if let id = json["id"] { 
      println(id) // prints 42 
     } 
    } 
    // With value as AnyObject 
    if let json = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as? [String:AnyObject] { 
     if let number = json["id"] as? Int { 
      println(number) // prints 42 
     } 
    } 
} 

更新雨燕2.0

do { 
    let str = "{\"id\": 42}" 
    if let data = str.dataUsingEncoding(NSUTF8StringEncoding) { 
     // With value as Int 
     if let json = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String:Int] { 
      if let id = json["id"] { 
       print(id) // prints 42 
      } 
     } 
     // With value as AnyObject 
     if let json = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String:AnyObject] { 
      if let number = json["id"] as? Int { 
       print(number) // prints 42 
      } 
     } 
    } 
} catch { 
    print(error) 
}