您可以直接使用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
}
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)
}
'讓nsDict = NSJSONSerialzation.whatever();讓swiftDict:[String:AnyObject] = nsDict as [String:AnyObject];' –