で直接 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
}
アップデート:
データが nil の可能性がある場合は、エラーを回避するために安全なアンラップを使用する必要があります。
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)
}