Last active
August 29, 2015 14:06
-
-
Save infolock/45bfba59fd078cdd7017 to your computer and use it in GitHub Desktop.
Swift JSON Parse
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 Foundation | |
// This can go in its own separate swift file - just keeping it here for reference.. | |
struct MyModel { | |
let name: String | |
let email: String | |
static func create( name: String, email: String ) -> MyModel { | |
return MyModel( name: name, email: email ) | |
} | |
} | |
class MyCollection { | |
var data: Array<MyModel> = [] | |
class func fetch() -> MyCollection { | |
var collection: Array<MyModel> = [] | |
let path = NSBundle.mainBundle().pathForResource( "myfile", ofType: "json" ) | |
if( path != nil ) { | |
let jsonData = NSData.dataWithContentsOfFile( path!, options: .DataReadingMappedIfSafe, error: nil ) | |
if( jsonData != nil ) { | |
let jsonObject : AnyObject! = NSJSONSerialization.JSONObjectWithData( jsonData!, options: NSJSONReadingOptions.MutableContainers, error: nil) | |
if let jsonArray = jsonObject as? NSArray{ | |
// Example of iterating through the JSON array we get from the response. | |
jsonArray.enumerateObjectsUsingBlock({ model, index, stop in | |
let name = model["name"] as String | |
let email = model["email"] as String | |
let modelStruct = MyModel.create( name, email: email ) | |
collection.append( modelStruct ) | |
}); | |
} | |
} | |
} | |
let instance = MyCollection() | |
instance.data = collection; | |
return instance; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Simple example of parsing a JSON string using swift
Assumes there is a file in the app bundle with the name of
myfile.json
having contents like the below:Example Usage with a UIViewController having a CollectionView: