Last active
August 29, 2015 14:16
-
-
Save Pretz/ffcbd6ebe493acabd470 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// Playground - noun: a place where people can play | |
import UIKit | |
class LumaJSONObject: Printable { | |
var value: AnyObject? | |
subscript(index: Int) -> LumaJSONObject? { | |
return (value as? [AnyObject]).map { LumaJSONObject($0[index]) } | |
} | |
subscript(key: String) -> LumaJSONObject? { | |
return (value as? NSDictionary).map { LumaJSONObject($0[key]) } | |
} | |
subscript(key: String) -> AnyObject? { | |
return self[key]?.value | |
} | |
subscript(key: Int) -> AnyObject? { | |
return self[key]?.value | |
} | |
init(_ value: AnyObject?) { | |
self.value = value | |
} | |
var description: String { | |
get { | |
return "LumaJSONObject: \(self.value)" | |
} | |
} | |
} | |
class LumaJSON { | |
func parse(json: String) -> LumaJSONObject? { | |
if let jsonData = json.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false){ | |
var err: NSError? | |
let parsed: AnyObject? = NSJSONSerialization.JSONObjectWithData(jsonData, options: .MutableLeaves, error: &err) | |
if let parsedArray = parsed as? NSArray { | |
return LumaJSONObject(parsedArray) | |
} | |
if let parsedDictionary = parsed as? NSDictionary { | |
return LumaJSONObject(parsedDictionary) | |
} | |
return LumaJSONObject(parsed) | |
} | |
return nil | |
} | |
} | |
let jsonStr = "{\"user\":{\"name\":\"jquave\",\"id\":542,\"url\":\"http://jamesonquave.com\"},\"friend_ids\":[299,341,492],\"alert_message\":\"Please verify e-mail address to continue\"}" | |
let luma = LumaJSON() | |
if let parsed = luma.parse(jsonStr) { | |
// Simple Key/Value retreival | |
if let alertMessage = parsed["alert_message"] as? String { | |
println("Alert: \(alertMessage)") | |
} | |
// Nested JSON | |
if let userName = parsed["user"]?["name"] as? String { | |
println("Username is \(userName)") | |
} | |
// Nested object casting works using Swift's built-in mechanisms | |
if let friendIDs = parsed["friend_ids"] as? [Int] { | |
for friendID in friendIDs { | |
println("Friend ID: \(friendID)") | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Much simpler: