Skip to content

Instantly share code, notes, and snippets.

@exorcyze
Last active August 29, 2015 14:06
Show Gist options
  • Save exorcyze/488dc26c46e7b8fdc6a7 to your computer and use it in GitHub Desktop.
Save exorcyze/488dc26c46e7b8fdc6a7 to your computer and use it in GitHub Desktop.
Sample Swift JSON Parsing
// *** Extensions
extension NSString {
func dictionaryFromJson() -> NSDictionary {
let jsonData = self.dataUsingEncoding( NSUTF8StringEncoding )!
return jsonData.dictionary()
}
}
extension String {
func dictionaryFromJson() -> NSDictionary {
let jsonData = self.dataUsingEncoding( NSUTF8StringEncoding )!
return jsonData.dictionary()
}
}
extension NSData {
func dictionary() -> NSDictionary {
var error : NSError?
return NSJSONSerialization.JSONObjectWithData( self, options: NSJSONReadingOptions.MutableContainers, error: &error ) as NSDictionary
}
// quick test function for downloading remote data
class func getJsonDataFromURL( url : String ) -> NSData {
return NSData( contentsOfURL: NSURL( string : url ) )
}
class func getJsonDataFromUrlAsync( url: String, completion: ( ( dict: NSDictionary, error: NSError? ) -> () ) ) {
let request = NSURLRequest(URL: NSURL( string: url )! )
NSURLConnection.sendAsynchronousRequest( request, queue: NSOperationQueue.mainQueue(), completionHandler: {(response: NSURLResponse!,data: NSData!,error: NSError!) -> Void in
if let error = error { completion( dict: NSDictionary(), error: error ); return }
completion( dict: data.dictionary(), error: nil )
})
}
}
extension NSDictionary {
/// Returns a "safe" value cast to the type of the fallback condition.
/// If the key ( or value ) are missing, then it returns the "or"
/// let mystr = mydict.safe( "testKey", or: "Default Value" )
func safe<T>( forKey: String, or: T ) -> T {
return self[ forKey ] as? T ?? or
}
}
// *** Sample Usage
let jsonString : NSString = ( "{\"id\":34, \"name\":\"John\", \"email\":\"[email protected]\"}" as NSString )
let mydata : Dictionary = jsonString.dictionaryFromJson()
let myuser : UserModel = UserModel( mydata )
// *** Sample Model Class
public struct UserModel {
public var id
public var name
public var email
public var missing
init( fromDictionary d : NSDictionary ) {
id = d.safe( "id", or: 0 )
name = d.safe( "name", or: "" )
email = d.safe( "email", or: "" )
missingItem = d.safe( "missing", or: "" )
}
}
// MARK: - Printable Extension
extension UserModel : Printable {
// allows us to just use println( myuser )
public var description : String {
return "USER ID \(self.id) : \(self.name) : \(self.email)"
}
}
// MARK: - Equatable Extension
extension UserModel : Equatable {}
public func ==( lhs : UserModel, rhs : UserModel ) -> Bool {
return lhs.id == rhs.id && lhs.name == rhs.name && lhs.email == rhs.email
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment