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

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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With