3

我有一个需要序列化为字典的 json 对象。我知道我可以将它序列化为 NSDictionary 但因为

“在 Swift 1.2 中,具有本机 Swift 等效项(NSString、NSArray、NSDictionary 等)的 Objective-C 类不再自动桥接。”

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

我宁愿把它放在本机 swift 字典中,以避免尴尬的桥接。

我不能使用 NSJSONSerialization 方法,因为它只映射到 NSDictionay。将 JSON 序列化为 swift 字典的另一种方法是什么?

4

1 回答 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
}

游乐场截图

更新:

如果您的数据可能为零,则必须使用安全展开以避免错误:

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)
}
于 2015-04-19T12:38:55.243 回答