NSJSONSerialization转换为Swift字典

3

我有一个 JSON 对象,需要将其序列化为字典。 我知道可以将其序列化为 NSDictionary,但是由于 "在 Swift 1.2 中,具有本地 Swift 等效项的 Objective-C 类(如 NSString、NSArray、NSDictionary 等)不再自动桥接。"

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

我更愿意将其放置在本地的 Swift 字典中,以避免尴尬的桥接。

我不能使用 NSJSONSerialization 方法,因为它仅映射到 NSDictionay。有没有另一种将 JSON 序列化为 Swift 字典的方法?


let nsDict = NSJSONSerialzation.whatever(); let swiftDict: [String:AnyObject] = nsDict as [String:AnyObject]; - The Paramagnetic Croissant
1个回答

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 截图

更新:

如果你的数据可能为空,你必须使用安全解包以避免错误:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接