Codable is added with Xcode 9, iOS 11 and Swift 4. Codable is used to make your data types encodable and decodable for compatibility with external representations such as JSON.
Codable use to support both encoding and decoding, declare conformance to Codable, which combines the Encodable and Decodable protocols. This process is known as making your types codable.
Let’s Take an Example with Structure of Movie, here we have defined the structure as Codable. So, We can encode and decode it easily.
JSON Parsing
How to create a wrapper for Alamofire and SwiftyJSON? Swift – iOS
This blogpost updated with Swift 3 – Xcode 8 – iOS 10 – Alamofire 4.0
I have posted a basic tutorial about Alamofire and SwiftyJSON How to use Alamofire and SwiftyJSON with Swift?
And some day before we have learned about Use of Blocks(Closures) or Completion Handlers with Function in Swift – iOS
Let’s combine both the topics to make a WRAPPER of Alamofire and SwiftyJSON.
How to use Alamofire and SwiftyJSON with Swift? – Swift 3 – iOS 10 – Xcode 8
Alamofire is an HTTP networking library written in Swift.
SwiftyJSON makes it easy to deal with JSON data in Swift.
Update : JSON Array Parsing in Swift Language – Swift 3 – iOS 10 – Xcode 8
So, how to parse following type of JSON?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
"contacts": [ { "id": "c200", "name": "Ashish Kakkad", "email": "ashishhkakkad@gmail.com", "address": "xx-xx-xxxx,x - street, x - country", "gender" : "male", "phone": { "mobile": "+91 0000000000", "home": "00 000000", "office": "00 000000" } }, { "id": "c201", "name": "Johnny Depp", "email": "johnny_depp@gmail.com", "address": "xx-xx-xxxx,x - street, x - country", "gender" : "male", "phone": { "mobile": "+91 0000000000", "home": "00 000000", "office": "00 000000" } } ] |
Create JSON Array Object :
1 2 3 4 5 6 7 8 9 |
let url=URL(string:"https://ashishkakkad.com/contacts.json") do { let allContactsData = try Data(contentsOf: url!) let allContacts = try JSONSerialization.jsonObject(with: allContactsData, options: JSONSerialization.ReadingOptions.allowFragments) as! [String : AnyObject] if let arrJSON = allContacts["contacts"] { } } catch { } |
Parse JSON Array Object :
1 2 3 4 5 6 7 8 9 |
if let arrJSON = allContacts["contacts"] { for index in 0...arrJSON.count-1 { let aObject = arrJSON[index] as! [String : AnyObject] names.append(aObject["name"] as! String) contacts.append(aObject["email"] as! String) } } print(names) print(contacts) |
Complete code snippet with UITableView:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
// // ViewController.swift // SwiftJSONParsingDemo // // Created by Ashish Kakkad on 12/10/16. // Copyright © 2016 Kode. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var tableView: UITableView! var names: [String] = [] var contacts: [String] = [] override func viewDidLoad() { super.viewDidLoad() let url=URL(string:"https://ashishkakkad.com/contacts.json") do { let allContactsData = try Data(contentsOf: url!) let allContacts = try JSONSerialization.jsonObject(with: allContactsData, options: JSONSerialization.ReadingOptions.allowFragments) as! [String : AnyObject] if let arrJSON = allContacts["contacts"] { for index in 0...arrJSON.count-1 { let aObject = arrJSON[index] as! [String : AnyObject] names.append(aObject["name"] as! String) contacts.append(aObject["email"] as! String) } } print(names) print(contacts) self.tableView.reloadData() } catch { } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func tableView(_ tableView: UITableView!, numberOfRowsInSection section: Int) -> Int { return self.names.count; } func tableView(_ tableView: UITableView!, didSelectRowAtIndexPath indexPath: IndexPath!) { print("You selected name : "+names[indexPath.row]) } func tableView(_ tableView: UITableView, cellForRowAtIndexPath indexPath: IndexPath) -> UITableViewCell{ var cell = tableView.dequeueReusableCell(withIdentifier: "cell") if !(cell != nil) { cell = UITableViewCell(style: .subtitle, reuseIdentifier: "cell") } cell?.textLabel?.text=self.names[indexPath.row] cell?.detailTextLabel?.text = self.contacts[indexPath.row] return cell! } } |
Posted a gist on github.
Helping, Learning, Coding 🙂
JSON Parsing in Swift Language – iOS 8
Here is tutorial about parsing JSON in Swift Language iOS 8
Create a Dictionary of all JSON data:
[code language=”obj-c”]
let url=NSURL(string:"http://api.androidhive.info/contacts/")
let allContactsData=NSData(contentsOfURL:url)
var allContacts:Dictionary<String, AnyObject>=NSJSONSerialization.JSONObjectWithData(allContactsData, options: NSJSONReadingOptions.MutableContainers, error: nil) as Dictionary<String, AnyObject>
NSLog("%@", allContacts)
[/code]
Parse the JSON by finding your key:
[code language=”obj-c”]
let contacts : AnyObject? = allContacts["contacts"]
for contacts in allContacts.keys {
println("All = \(contacts)")
let contact : AnyObject? = allContacts[contacts]
let collection = contact! as Array<Dictionary<String, AnyObject>>
for subContact in collection {
let name : AnyObject? = subContact["name"]
let email : AnyObject? = subContact["email"]
names+=name! as String
emails+=email! as String
println("Name: \(name)")
println("Email: \(email)")
}
}
[/code]
Complete code snippet with UITableView:
[code language=”obj-c”]
import UIKit
class ViewController: UIViewController,UITableViewDelegate, UITableViewDataSource
{
@IBOutlet var tblJson : UITableView = nil
var names: String[] = []
var emails: String[] = []
override func viewDidLoad() {
super.viewDidLoad()
let url=NSURL(string:"http://api.androidhive.info/contacts/")
let allContactsData=NSData(contentsOfURL:url)
var allContacts:Dictionary<String, AnyObject>=NSJSONSerialization.JSONObjectWithData(allContactsData, options: NSJSONReadingOptions.MutableContainers, error: nil) as Dictionary<String, AnyObject>
NSLog("%@", allContacts)
let contacts : AnyObject? = allContacts["contacts"]
for contacts in allContacts.keys {
println("All = \(contacts)")
let contact : AnyObject? = allContacts[contacts]
let collection = contact! as Array<Dictionary<String, AnyObject>>
for subContact in collection {
let name : AnyObject? = subContact["name"]
let email : AnyObject? = subContact["email"]
names+=name! as String
emails+=email! as String
println("Name: \(name)")
println("Email: \(email)")
}
}
println(names)
println(emails)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
return self.names.count;
}
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
var cell = tableView.dequeueReusableCellWithIdentifier("cell") as? UITableViewCell
if !cell {
cell = UITableViewCell(style: .Subtitle, reuseIdentifier: "cell")
}
cell!.textLabel.text = self.names[indexPath.row]
cell!.detailTextLabel.text = self.emails[indexPath.row]
return cell
}
func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
println("You selected name : "+names[indexPath.row])
}
}
[/code]
Helping, Learning, Coding 🙂