JSON, which is the abbreviation of JavaScript Object Notation, is the most popular data transfer format for app developers. We already learned about Swift JSON Parsing in one of the previous posts. But before Swift 4 parsing JSON data was really painful, so many developers were using SwiftyJSON like libraries. But Swift 4 has introduced Codable protocol making the JSON parsing easier than ever. So in this Swift Codable Example, we will learn how you can use Codable for parsing JSON data fetched from a URL.
Contents
Pre – Requisites
This post is specifically about a Swift Codable Example. So what we are going to learn here is Parsing JSON data using Codable protocol. But some other thing is also involved. So before moving ahead it is a good idea that you go through the below Alamofire tutorial.
As in this post I will be using Alamofire for fetching JSON data from a URL.
And if you don’t know anything about JSON then you need to check this quick JSON video as well.
The Basics of JSON Parsing using Codable
Let’s understand with the example that I will be using here in the project. So I have a URL that returns some JSON data. The URL is
https://www.simplifiedcoding.net/demos/marvel/
If you will go to the above URL, it will display the following data.
You can see in the above data we have a JSON array, that is having a number of JSON objects. Now if we want to parse the above JSON objects using Swift Codable then first we need to define a structure.
Define Structure of Parsing JSON
For the above data we can create a structure as below.
struct Hero : Codable{ let name:String? let realname: String? let team: String? let firstappearance: String? let createdby: String? let publisher: String? let imageurl: String? let bio: String? }
Remember here the name of variables are exactly the same as the JSON keys, in the actual data. In case you want to use different names for variable you can create the structure as below.
struct Hero : Codable{ let heroName:String? let realName: String? let team: String? let firstappearance: String? let createdby: String? let publisher: String? let imageurl: String? let bio: String? private enum CodingKeys: String, CodingKey { case heroName = "name" case realName = "realname" case team case firstappearance case createdby case publisher case imageurl case bio } }
In the above code the first two having different variable names, so to match them with the JSON keys we create a CodingKeys enum where we define the real keys as I defined above, for the variables that has the same name as the Keys in the JSON data, defining the key name is not necessary.
Parsing JSON Data
Now let’s understand the main thing which is parsing the data.
let decoder = JSONDecoder() parsedData = decoder.decode(YourStructure.self, from: YourJsonData)
So, parsing data is really very easy, as you can see only two lines and the work is done.
- Step 1: Create a JSONDecoder().
- Step 2: Call the function decode from the JSONDecoder. It takes two parameter the first is your Structure and the second is the JSON data.
Swift Codable Example
So, enough for the basics. Now let’s try implementing it in our Xcode project.
Creating a new Xcode Project
- As always first we need a new Xcode Project. So for this example I have created a Single View App named SwiftJSONExample.
Adding Alamofire
- Now we need to add Alamofire dependency to the project. For this we need to use Cocoa Pods, and if you don’t know how to do this, then in short the steps are
- Create a Podfile (Use pod init command)
- Open the Podfile (put the alamofire dependency)
- Run the command Pod Install
- Open project.xcworkspace.
- If you are confused what I said above then you should definitely go through this Adding Alamofire Tutorial First.
- For adding Alamofire, here is my Podfile.
# Uncomment the next line to define a global platform for your project # platform :ios, '9.0' target 'SwiftJSONExample' do # Comment the next line if you're not using Swift and don't want to use dynamic frameworks use_frameworks! # Pods for SwiftJSONExample pod 'Alamofire', '~> 4.7' target 'SwiftJSONExampleTests' do inherit! :search_paths # Pods for testing end target 'SwiftJSONExampleUITests' do inherit! :search_paths # Pods for testing end end
Fetching JSON data using Alamofire
- Now come to ViewController.swift.
class ViewController: UIViewController { //defining the API URL let API_URL = "https://www.simplifiedcoding.net/demos/marvel/" override func viewDidLoad() { super.viewDidLoad() //Performing an Alamofire request to get the data from the URL Alamofire.request(API_URL).responseJSON { response in //now here we have the response data that we need to parse let json = response.data } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
- The above code is very simple, we are just fetching the response of the URL using Alamofire. Now our next task is to parse the data that is fetched.
Parsing the JSON Data using Codable
Creating the Structure
- First we need our structure. So for the JSON that we are using, we can use the below structure.
struct Hero : Codable{ let name:String? let realname: String? let team: String? let firstappearance: String? let createdby: String? let publisher: String? let imageurl: String? let bio: String? }
- Put the above structure, just above the ViewController class.
Creating an Array
- As the response we are getting from the URL is not a single object, it is an array of JSON objects. So to parse the array we need an Array of the structure that we created above.
- So inside the class ViewController create an array as below.
var heroes = [Hero]()
Parsing the Data
- Finally inside Alamofire where we are getting the response data we will parse it.
Alamofire.request(API_URL).responseJSON { response in let json = response.data do{ //created the json decoder let decoder = JSONDecoder() //using the array to put values self.heroes = try decoder.decode([Hero].self, from: json!) //printing all the hero names for hero in self.heroes{ print(hero.name!) } }catch let err{ print(err) } }
- The above code is very simple and self explanatory.
The final code
- If you are confused here is the final code of ViewController.swift.
// // ViewController.swift // SwiftJSONExample // // Created by Belal Khan on 05/06/18. // Copyright © 2018 Belal Khan. All rights reserved. // import UIKit import Alamofire struct Hero : Codable{ let name:String? let realname: String? let team: String? let firstappearance: String? let createdby: String? let publisher: String? let imageurl: String? let bio: String? } class ViewController: UIViewController { var heroes = [Hero]() //defining the API URL let API_URL = "https://www.simplifiedcoding.net/demos/marvel/" override func viewDidLoad() { super.viewDidLoad() Alamofire.request(API_URL).responseJSON { response in let json = response.data do{ //created the json decoder let decoder = JSONDecoder() //using the array to put values self.heroes = try decoder.decode([Hero].self, from: json!) //printing all the hero names for hero in self.heroes{ print(hero.name!) } }catch let err{ print(err) } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
- Now you can run your application and you will get the following output.
- Bingo! we have all the values. Now you can display everything in a List. For this you can check the Custom UITableView Tutorial.
Swift Codable Example Source Code
If you are having still some issues following the post you can get my source code from the below link.
[sociallocker] Swift Codable Example Source Code [/sociallocker]
So thats all for this tutorial friends. If you think it is useful share it with your friends. And anything you want to ask regarding this Swift Codable Example, don’t hesitate to leave your comments. Thank You 🙂
Eve says
Why are you using Alamofire and calling this a Swift Codable Example?
Belal Khan says
Alamofire is for handling network operation, and codable is for parsing json, here I need json from a URL so I need alamofire as well but the parsing part is done with codable.