Capture and parse JSON data in Swift

  • The sample code below shows how to get JSON encoded data via HTTP and then parse it for use within the application. For HTTP interaction, I am using SwiftHTTP (which I won’t be going into , for this post).

The code to parse JSON is done by a third party called SwiftyJSON which is available here: https://github.com/SwiftyJSON/SwiftyJSON

It is a single file which you can add to your Swift Project. I have made two functions in ViewController.swift which deals with the actual retrieving and parsing of the JSON data. JSON data is normally of one of the two types:

  • Array of objects – example in func getJSONFeedAsArray
  • Single Object – sample in func getJSONFeedAsObject

I am using public data repositories which provide data in the JSON format. You can check how the raw data looks for these urls:

https://api.github.com/users/hadley/orgs

https://www.bitstamp.net/api/ticker/

 

 

  func getJSONFeedAsArray() {
        let url = "https://api.github.com/users/hadley/orgs"
        var data:String = ""
        
        do {
            let opt = try HTTP.GET(url)
            opt.start { response in
                if let err = response.error {
                    print("error: \(err.localizedDescription)")
                    return //also notify app of failure as needed
                }
                if let _ = response.data as NSData?
                {
                    data = String(data: response.data, encoding: NSUTF8StringEncoding)!
                    
                    //parse JSON
                    if let dataFromString = data.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) {
                        let json = JSON(data: dataFromString)
                        
                        // the data is an array of objects so get the count of items and iterate through each
                        let count = json.count
                        for (var i=0; i < count; i++)
                        {
                            let login = json[i]["login"].stringValue
                            let id = json[i]["id"].intValue
                            let url = json[i]["url"].stringValue
                            let repos_url = json[i]["repos_url"].stringValue
                            
                            print(login)
                            print (id)
                            print (url)
                            print (repos_url)
                            print("-----------------")
                        }
                        
                        
                        // update UI in dispatch thread
                        dispatch_async(dispatch_get_main_queue(),{
                            // update UI here
                        })
                    }
                } // if let _ = response.data as NSData?
                
            }
        } catch let error {
            print("got an error creating the request: \(error)")
        }
        
    }

    func getJSONFeedAsObject() {
        let url = "https://www.bitstamp.net/api/ticker/"
        var data:String = ""
        
        do {
            let opt = try HTTP.GET(url)
            opt.start { response in
                if let err = response.error {
                    print("error: \(err.localizedDescription)")
                    return //also notify app of failure as needed
                }
                if let _ = response.data as NSData?
                {
                    data = String(data: response.data, encoding: NSUTF8StringEncoding)!
                    
                    //parse JSON
                    if let dataFromString = data.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) {
                        let json = JSON(data: dataFromString)
                        
                        let high = json["high"].floatValue
                        let last = json["last"].floatValue
                        let timestamp = json["timestamp"].stringValue
                        let bid = json["bid"].floatValue
                        let vwap = json["vwap"].floatValue
                        let volume = json["volume"].floatValue
                        
                        print(high)
                        print (last)
                        print (timestamp)
                        print (bid)
                        print (vwap)
                        print (volume)
                        
                        print("-----------------")
                        
                        
                        
                        // update UI in dispatch thread
                        dispatch_async(dispatch_get_main_queue(),{
                            // update UI here
                        })
                    }
                } // if let _ = response.data as NSData?
                
            }
        } catch let error {
            print("got an error creating the request: \(error)")
        }
        
    }

Be the first to comment

Leave a Reply

Your email address will not be published.


*


This site uses Akismet to reduce spam. Learn how your comment data is processed.