您可以直接将 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
}
更新:
如果您的数据可能为零,则必须使用安全展开以避免错误:
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
}
}
}
Swift 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)
}