Skip to content

Instantly share code, notes, and snippets.

@izotx
Created February 26, 2016 21:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save izotx/91dcf13702eec5b96b13 to your computer and use it in GitHub Desktop.
Save izotx/91dcf13702eec5b96b13 to your computer and use it in GitHub Desktop.
Parsing JSON With Swift
//: Playground - noun: a place where people can play
import UIKit
import XCPlayground
var str = "Hello, playground"
///https://developer.apple.com/library/watchos/recipes/Playground_Help/Chapters/AddResource.html
/**
{ "feed":
{
"apps": [
{
"name":"iTenWired",
"price":0,
"developer": "Izotx"
}
]
}
}
*/
let sharedImagePath = XCPlaygroundSharedDataDirectoryURL.path!
//print(sharedImagePath)
//stringByAppendingPathComponent("image.png")
// get the file path for the file "test.json" in the playground bundle
let filePath = NSBundle.mainBundle().pathForResource("sample", ofType: "json")
// get the contentData
let contentData = NSFileManager.defaultManager().contentsAtPath(filePath!)
func serializeAndParse(){
do {
//Serialize it
let dictionary = try NSJSONSerialization.JSONObjectWithData(contentData!, options: .MutableContainers) as! NSDictionary
//parse lazy way
parseLazyWay(dictionary)
let data = betterParsing(dictionary)
data.apps
}
catch let error as NSError {
print(error)
}
}
/**Quick and dirty parsing - not recommended in a long run */
func parseLazyWay(dictionary:NSDictionary){
if let feed = dictionary.objectForKey("feed"){
feed
}
if let feed = dictionary.objectForKey("feed") as? NSDictionary, apps = feed.objectForKey("apps")as? NSArray{
feed
apps
//print name =
apps[0].objectForKey("name")
}
}
//Better method
func betterParsing(dictionary:NSDictionary)->Data{
let data = Data()
if let feed = dictionary.objectForKey("feed"){
feed
}
if let feed = dictionary.objectForKey("feed") as? NSDictionary, apps = feed.objectForKey("apps")as? NSArray{
for appString in apps{
if let appDict = appString as? NSDictionary{
data.addApp(appDict)
}
}
}
return data
}
/**Used by better parsing*/
class Data {
var apps = [App]()
func addApp(dictionary:NSDictionary){
apps.append(App(dictionary: dictionary))
}
}
/*App Enum - listing the keys in app's dictionary */
enum AppEnum:String{
case developer
case price
case name
}
/**Data Structure of the app*/
class App {
var name = ""
var price = 0.0
var developer = "Apple"
/**Convieniene initializer - pass dictionary to create a new instance of the application */
init(dictionary:NSDictionary){
if let developer = dictionary.objectForKey(AppEnum.developer.rawValue) as? String{
self.developer = developer
}
if let price = dictionary.objectForKey(AppEnum.price.rawValue) as? Double{
self.price = price
}
if let name = dictionary.objectForKey(AppEnum.name.rawValue) as? String{
self.name = name
}
}
}
serializeAndParse()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment