Simplified iOS

  • Home
  • About
  • Contact
  • Advertise
  • Write for Us

Swift Codable Example: Fetching and Parsing JSON

June 5, 2018 by Belal Khan 2 Comments

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

  • 1 Pre – Requisites
  • 2 The Basics of JSON Parsing using Codable
    • 2.1 Define Structure of Parsing JSON
    • 2.2 Parsing JSON Data
  • 3 Swift Codable Example
    • 3.1 Creating a new Xcode Project
    • 3.2 Adding Alamofire
    • 3.3 Fetching JSON data using Alamofire
    • 3.4 Parsing the JSON Data using Codable
      • 3.4.1 Creating the Structure
      • 3.4.2 Creating an Array
      • 3.4.3 Parsing the Data
      • 3.4.4 The final code
  • 4 Swift Codable Example Source Code
    • 4.1 Share this:
    • 4.2 Related

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.

  • Using Alamofire in Your Xcode Project

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.

Swift Codable Example

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.
Swift Codable Example

Swift Codable Example

  • 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 🙂

Share this:

  • Tweet
  • Share on Tumblr
  • WhatsApp

Related

Filed Under: iOS Development Tutorial Tagged With: swift codable, swift json, swift4

About Belal Khan

I am Belal Khan, I am currently pursuing my MCA. In this blog I write tutorials and articles related to coding, app development, iphone etc.

Comments

  1. Eve says

    June 6, 2018 at 1:44 am

    Why are you using Alamofire and calling this a Swift Codable Example?

    Reply
    • Belal Khan says

      August 1, 2018 at 5:23 am

      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.

      Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *




About Me

belal khan simplified ios

Hello I am Belal Khan, founder and owner of Simplified iOS. I am currently pursuing MCA from St. Xavier's College, Ranchi. Apart from my academic I am a blogger, I run various websites and majority of them are about coding and development.

Connect with Me

Follow Simplified iOS

Simplified iOS

Popular Posts

  • Swift SQLite Tutorial for Beginners – Using… (99,380)
  • Swift PHP MySQL Tutorial – Connecting iOS App… (98,248)
  • UIWebView Example to Load URL in iOS using Swift in Xcode (79,974)
  • Download Full High Sierra Installer to Create Bootable USB (70,273)
  • Xcode Login Screen Example using Swift 3, PHP and MySQL (67,256)
  • How to Format USB on Mac? Formatting External Hard… (61,373)
  • Swift JSON Tutorial – Fetching and Parsing… (59,402)
  • Firebase Realtime Database Tutorial for Swift using Xcode (53,697)
  • iOS Registration Form Example using PHP and MySQL (48,915)
  • Xcode Text Field Tutorial for iOS Application using Swift (41,145)




About

Simplified iOS is a blog where you can find latest tutorials related to coding and app development for iphone and MAC OS. Here you can get Simplified iPhone, iPad and Mac OS development tutorial to know the things about Apple Development from basics to advanced level.

Quick Links

  • Advertise
  • Contact
  • Disclaimer
  • Privacy Policy
  • Write for Us

Copyright © 2017 · Simplified iOS· All rights Reserved. And Our Sitemap.All Logos & Trademark Belongs To Their Respective Owners·