-
-
Save joshuatbrown/dc5da6d8eb4919e545ec to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Cocoa | |
import Foundation | |
let jsonString = "{\"username\": \"josh\"}" | |
let data = jsonString.dataUsingEncoding(NSUTF8StringEncoding)! | |
// UNSAFE JSON PARSING | |
//var jsonError: NSError? | |
//let json = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: &jsonError) as NSDictionary | |
// | |
//if let unwrappedError = jsonError { | |
// println("json error: \(unwrappedError)") | |
//} else { | |
// let username = json.valueForKeyPath("username") as String | |
// println("username: \(username)") | |
//} | |
// SAFE JSON PARSING | |
var jsonError: NSError? | |
if let json = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: &jsonError) as? [String: AnyObject] { | |
if let unwrappedError = jsonError { | |
println("json error: \(unwrappedError)") | |
} else { | |
if let username = json["username"] as? String { | |
println("username: \(username)") | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hello, in "safe json parsing" section: should not you move out jsonError from successful "if let" as below?
if let json = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: &jsonError) as? [String: AnyObject] {
if let username = json["username"] as? String {
println("username: (username)")
}
} else {
if let unwrappedError = jsonError {
println("json error: (unwrappedError)")
}
}