Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSJSONSerialization into swift dictionary

I have a json object I need to serialise into a dictionary. I know I can have it serialised into a NSDictionary but since

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

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

I rather have it in native swift dictionary to avoid awkward bridging.

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

like image 373
Jacky Wang Avatar asked Dec 20 '25 23:12

Jacky Wang


1 Answers

You can use a Swift dictionary directly with 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 may be nil, you have to use safe unwrapping 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)
}
like image 114
Eric Aya Avatar answered Dec 23 '25 15:12

Eric Aya



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!