Skip to content

Instantly share code, notes, and snippets.

@infolock
Last active August 29, 2015 14:06
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 infolock/45bfba59fd078cdd7017 to your computer and use it in GitHub Desktop.
Save infolock/45bfba59fd078cdd7017 to your computer and use it in GitHub Desktop.
Swift JSON Parse
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;
}
}
@infolock
Copy link
Author

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:

[
    {
           "name": "John Doe",
           "email": "john.doe@example.com"
    },
    {
           "name": "Billy Bob",
           "email": "billy.bob@yeehaw.com"
    }
]

Example Usage with a UIViewController having a CollectionView:

import UIKit

class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {

    @IBOutlet weak var collectionView: UICollectionView!

    struct CollectionViewSettings {
        static let identifier = "myCell"
    }

    var Items: MyCollection = {
        return MyCollection.fetch()
    }()

    var cellCount = 0;

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return Items.data.count
    }

    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        var cell = collectionView.dequeueReusableCellWithReuseIdentifier( CollectionViewSettings.identifier, forIndexPath: indexPath) as MyCollectionViewCell
        cell.loadWithItems( Items.data[indexPath.row] )

        return cell
    }
}

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