NSJSONSerialization to swift dictionary

I have a json object that I need to serialize into a dictionary. I know this can be serialized to NSDictionary, but since

"in Swift 1.2, Objective-C classes that have their own Swift equivalents (NSString, NSArray, NSDictionary, etc.) are no longer automatically concatenated."

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

I prefer it in the native swift dictionary to avoid the awkward bridge.

I cannot use NSJSONSerialization method as it only maps to NSDictionay. What's another way to serialize JSON into a swift dictionary?

+3


source to share


1 answer


With a Swift dictionary you can use directly NSJSONSerialization

.

Example for {"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

      

Or with 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 screenshot



UPDATE:

If your data might be null, you need to use a safe unwrap to avoid errors:

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

      


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

      

+4


source







All Articles