【问题标题】:NSJSONSerialization into swift dictionaryNSJSONSerialization 成 swift 字典
【发布时间】:2015-06-26 01:47:47
【问题描述】:

我有一个需要序列化成字典的 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 字典的另一种方法是什么?

【问题讨论】:

  • let nsDict = NSJSONSerialzation.whatever(); let swiftDict: [String:AnyObject] = nsDict as [String:AnyObject];

标签: json swift nsdictionary swift-dictionary


【解决方案1】:

您可以直接将 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)
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-14
    • 2016-07-31
    • 1970-01-01
    • 2017-03-19
    相关资源
    最近更新 更多