Skip to content

Instantly share code, notes, and snippets.

@joshuatbrown
Last active Aug 29, 2015
Embed
What would you like to do?
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)")
}
}
}
@StanislavK

This comment has been minimized.

Copy link

@StanislavK StanislavK commented Feb 15, 2015

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment