{"id":2573,"date":"2015-12-30T14:18:00","date_gmt":"2015-12-30T14:18:00","guid":{"rendered":"http:\/\/truelogic.org\/wordpress\/?p=2573"},"modified":"2015-12-30T14:18:00","modified_gmt":"2015-12-30T14:18:00","slug":"capture-and-parse-json-data-in-swift","status":"publish","type":"post","link":"https:\/\/truelogic.org\/wordpress\/2015\/12\/30\/capture-and-parse-json-data-in-swift\/","title":{"rendered":"Capture and parse JSON data in Swift"},"content":{"rendered":"<ul>\n<li>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&#8217;t be going into , for this post).<\/li>\n<\/ul>\n<p>The code to parse JSON is done by a third party called SwiftyJSON which is available here:\u00a0<a href=\"https:\/\/github.com\/SwiftyJSON\/SwiftyJSON\" target=\"_blank\">https:\/\/github.com\/SwiftyJSON\/SwiftyJSON<\/a><\/p>\n<p>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:<\/p>\n<ul>\n<li>Array of objects &#8211; example in\u00a0<em>func\u00a0getJSONFeedAsArray<\/em><\/li>\n<li>Single Object &#8211; sample in\u00a0<em>func getJSONFeedAsObject<\/em><\/li>\n<\/ul>\n<p>I am using public data repositories which provide data in the JSON format. You can check how the raw data looks for these urls:<\/p>\n<p><a href=\"https:\/\/api.github.com\/users\/hadley\/orgs\" target=\"_blank\">https:\/\/api.github.com\/users\/hadley\/orgs<\/a><\/p>\n<p><a href=\"https:\/\/www.bitstamp.net\/api\/ticker\/\" target=\"_blank\">https:\/\/www.bitstamp.net\/api\/ticker\/<\/a><\/p>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n<pre>  func getJSONFeedAsArray() {\r\n        let url = \"https:\/\/api.github.com\/users\/hadley\/orgs\"\r\n        var data:String = \"\"\r\n        \r\n        do {\r\n            let opt = try HTTP.GET(url)\r\n            opt.start { response in\r\n                if let err = response.error {\r\n                    print(\"error: \\(err.localizedDescription)\")\r\n                    return \/\/also notify app of failure as needed\r\n                }\r\n                if let _ = response.data as NSData?\r\n                {\r\n                    data = String(data: response.data, encoding: NSUTF8StringEncoding)!\r\n                    \r\n                    \/\/parse JSON\r\n                    if let dataFromString = data.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) {\r\n                        let json = JSON(data: dataFromString)\r\n                        \r\n                        \/\/ the data is an array of objects so get the count of items and iterate through each\r\n                        let count = json.count\r\n                        for (var i=0; i &lt; count; i++)\r\n                        {\r\n                            let login = json[i][\"login\"].stringValue\r\n                            let id = json[i][\"id\"].intValue\r\n                            let url = json[i][\"url\"].stringValue\r\n                            let repos_url = json[i][\"repos_url\"].stringValue\r\n                            \r\n                            print(login)\r\n                            print (id)\r\n                            print (url)\r\n                            print (repos_url)\r\n                            print(\"-----------------\")\r\n                        }\r\n                        \r\n                        \r\n                        \/\/ update UI in dispatch thread\r\n                        dispatch_async(dispatch_get_main_queue(),{\r\n                            \/\/ update UI here\r\n                        })\r\n                    }\r\n                } \/\/ if let _ = response.data as NSData?\r\n                \r\n            }\r\n        } catch let error {\r\n            print(\"got an error creating the request: \\(error)\")\r\n        }\r\n        \r\n    }\r\n\r\n    func getJSONFeedAsObject() {\r\n        let url = \"https:\/\/www.bitstamp.net\/api\/ticker\/\"\r\n        var data:String = \"\"\r\n        \r\n        do {\r\n            let opt = try HTTP.GET(url)\r\n            opt.start { response in\r\n                if let err = response.error {\r\n                    print(\"error: \\(err.localizedDescription)\")\r\n                    return \/\/also notify app of failure as needed\r\n                }\r\n                if let _ = response.data as NSData?\r\n                {\r\n                    data = String(data: response.data, encoding: NSUTF8StringEncoding)!\r\n                    \r\n                    \/\/parse JSON\r\n                    if let dataFromString = data.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) {\r\n                        let json = JSON(data: dataFromString)\r\n                        \r\n                        let high = json[\"high\"].floatValue\r\n                        let last = json[\"last\"].floatValue\r\n                        let timestamp = json[\"timestamp\"].stringValue\r\n                        let bid = json[\"bid\"].floatValue\r\n                        let vwap = json[\"vwap\"].floatValue\r\n                        let volume = json[\"volume\"].floatValue\r\n                        \r\n                        print(high)\r\n                        print (last)\r\n                        print (timestamp)\r\n                        print (bid)\r\n                        print (vwap)\r\n                        print (volume)\r\n                        \r\n                        print(\"-----------------\")\r\n                        \r\n                        \r\n                        \r\n                        \/\/ update UI in dispatch thread\r\n                        dispatch_async(dispatch_get_main_queue(),{\r\n                            \/\/ update UI here\r\n                        })\r\n                    }\r\n                } \/\/ if let _ = response.data as NSData?\r\n                \r\n            }\r\n        } catch let error {\r\n            print(\"got an error creating the request: \\(error)\")\r\n        }\r\n        \r\n    }\r\n\r\n<\/pre>\n","protected":false},"excerpt":{"rendered":"<div class=\"mh-excerpt\"><p>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, <a class=\"mh-excerpt-more\" href=\"https:\/\/truelogic.org\/wordpress\/2015\/12\/30\/capture-and-parse-json-data-in-swift\/\" title=\"Capture and parse JSON data in Swift\">[&#8230;]<\/a><\/p>\n<\/div>","protected":false},"author":1,"featured_media":2409,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[310],"tags":[],"class_list":["post-2573","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-xcode-swift"],"_links":{"self":[{"href":"https:\/\/truelogic.org\/wordpress\/wp-json\/wp\/v2\/posts\/2573","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/truelogic.org\/wordpress\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/truelogic.org\/wordpress\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/truelogic.org\/wordpress\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/truelogic.org\/wordpress\/wp-json\/wp\/v2\/comments?post=2573"}],"version-history":[{"count":3,"href":"https:\/\/truelogic.org\/wordpress\/wp-json\/wp\/v2\/posts\/2573\/revisions"}],"predecessor-version":[{"id":2576,"href":"https:\/\/truelogic.org\/wordpress\/wp-json\/wp\/v2\/posts\/2573\/revisions\/2576"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/truelogic.org\/wordpress\/wp-json\/wp\/v2\/media\/2409"}],"wp:attachment":[{"href":"https:\/\/truelogic.org\/wordpress\/wp-json\/wp\/v2\/media?parent=2573"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/truelogic.org\/wordpress\/wp-json\/wp\/v2\/categories?post=2573"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/truelogic.org\/wordpress\/wp-json\/wp\/v2\/tags?post=2573"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}