Close Menu
  • Home
  • AI
  • Big Data
  • Cloud Computing
  • iOS Development
  • IoT
  • IT/ Cybersecurity
  • Tech
    • Nanotechnology
    • Green Technology
    • Apple
    • Software Development
    • Software Engineering

Subscribe to Updates

Get the latest technology news from Bigteetechhub about IT, Cybersecurity and Big Data.

    What's Hot

    “Bunker Mentality” in AI: Are We There Yet?

    October 14, 2025

    Israel Hamas deal: The hostage, ceasefire, and peace agreement could have a grim lesson for future wars.

    October 14, 2025

    Astaroth: Banking Trojan Abusing GitHub for Resilience

    October 13, 2025
    Facebook X (Twitter) Instagram
    Facebook X (Twitter) Instagram
    Big Tee Tech Hub
    • Home
    • AI
    • Big Data
    • Cloud Computing
    • iOS Development
    • IoT
    • IT/ Cybersecurity
    • Tech
      • Nanotechnology
      • Green Technology
      • Apple
      • Software Development
      • Software Engineering
    Big Tee Tech Hub
    Home»iOS Development»How to parse JSON in Swift using Codable protocol?
    iOS Development

    How to parse JSON in Swift using Codable protocol?

    big tee tech hubBy big tee tech hubJuly 16, 2025003 Mins Read
    Share Facebook Twitter Pinterest Copy Link LinkedIn Tumblr Email Telegram WhatsApp
    Follow Us
    Google News Flipboard
    How to parse JSON in Swift using Codable protocol?
    Share
    Facebook Twitter LinkedIn Pinterest Email Copy Link


    1/29/18 3:20 PM
    · 1 min read


    In this Swift tutorial, I’d like to give you an example about getting and parsing JSON data using URLSession and Codable protocol.

    Dependencies

    First of all just a few words about dependencies. From Swift 4 you don’t need any dependency to parse JSON data, because there are built-in protocols to take care of everything. If you are still using some kind of 3rd-party you should definitely ditch it for the sake of simplicity. By the way before you add any external dependency into your project, please think twice. 🤔

    Networking

    If your task is simply to load some kind of JSON document through HTTP from around the web, – surprise – you won’t need Alamofire at all. You can use the built-in URLSession class to make the request, and get back everything that you’ll need. The Foundation networking stack is already a complex and very useful stack, don’t make things even more complicated with extra layers.

    JSON parsing

    Now, after the short intro, let’s dive in and get some real fake JSON data from the JSONPlaceholder web service. I’m going to place the whole thing right here, you can select it, copy and paste into a Swift playground file.

    import Foundation
    import PlaygroundSupport
    
    PlaygroundPage.current.needsIndefiniteExecution = true
    
    struct Post: Codable {
    
        enum CodingKeys: String, CodingKey {
            case id
            case title
            case body
            case userIdentifier = "userId"
        }
    
        let id: Int
        let title: String
        let body: String
        let userIdentifier: Int
    }
    
    let url = URL(string: "
    
    URLSession.shared.dataTask(with: url) { data, response, error in
        if let error = error {
            print("Error: \(error.localizedDescription)")
            PlaygroundPage.current.finishExecution()
        }
        guard 
            let httpResponse = response as? HTTPURLResponse, 
            httpResponse.statusCode == 200 
        else {
            print("Error: invalid HTTP response code")
            PlaygroundPage.current.finishExecution()
        }
        guard let data = data else {
            print("Error: missing data")
            PlaygroundPage.current.finishExecution()
        }
    
        // feel free to uncomment this for debugging data
        // print(String(data: data, encoding: .utf8))
    
        do {
            let decoder = JSONDecoder()
            let posts = try decoder.decode([Post].self, from: data)
    
            print(posts.map { $0.title })
            PlaygroundPage.current.finishExecution()
        }
        catch {
            print("Error: \(error.localizedDescription)")
            PlaygroundPage.current.finishExecution()
        }
    }.resume()
    

    As you can see downloading and parsing JSON from the web is a really easy task. This whole code snippet is around 50 lines of code. Of course it’s just a proof of concept, but it works and you don’t need any dependency. It’s pure Swift and Foundation.

    To save some typing, you can also generate the final objects directly from the JSON structure with these amazing Xcode extensions.

    The Codable protocol – which is actually a compound typealias from Encodable & Decodable protocols – makes the process of parsing JSON data in Swift magical. 💫


    How to parse JSON in Swift using Codable protocol?

    Share this article

    Thank you. 🙏

    Related posts

    featured

    How to parse JSON in Swift using Codable protocol?

    6/26/25 11:00 AM
    · 8 min read


    Learn how to implement user-friendly, type-safe error handling in Swift 6 with structured diagnostics and a hierarchical error model.

    How to parse JSON in Swift using Codable protocol?

    9/10/21 2:20 PM
    · 6 min read


    Learn everything about logical types and the Boolean algebra using the Swift programming language and some basic math.

    How to parse JSON in Swift using Codable protocol?

    3/18/22 3:20 PM
    · 4 min read


    Learn how to communicate with API endpoints using the brand new SwiftHttp library, including async / await support.

    How to parse JSON in Swift using Codable protocol?

    2/5/19 3:20 PM
    · 9 min read


    The one and only tutorial that you’ll ever need to learn higher order functions like: map, flatMap, compactMap, reduce, filter and more.



    Source link

    Codable JSON parse protocol Swift
    Follow on Google News Follow on Flipboard
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email Copy Link
    tonirufai
    big tee tech hub
    • Website

    Related Posts

    ios – Differences in builds between Xcode 16.4 and Xcode 26

    October 13, 2025

    ios – Apple mapkit route function dose not works in China

    October 12, 2025

    swift – Does UIDevice.current.identifierForVendor change after iCloud backup and restore on another iOS device?

    October 11, 2025
    Add A Comment
    Leave A Reply Cancel Reply

    Editors Picks

    “Bunker Mentality” in AI: Are We There Yet?

    October 14, 2025

    Israel Hamas deal: The hostage, ceasefire, and peace agreement could have a grim lesson for future wars.

    October 14, 2025

    Astaroth: Banking Trojan Abusing GitHub for Resilience

    October 13, 2025

    ios – Differences in builds between Xcode 16.4 and Xcode 26

    October 13, 2025
    Advertisement
    About Us
    About Us

    Welcome To big tee tech hub. Big tee tech hub is a Professional seo tools Platform. Here we will provide you only interesting content, which you will like very much. We’re dedicated to providing you the best of seo tools, with a focus on dependability and tools. We’re working to turn our passion for seo tools into a booming online website. We hope you enjoy our seo tools as much as we enjoy offering them to you.

    Don't Miss!

    “Bunker Mentality” in AI: Are We There Yet?

    October 14, 2025

    Israel Hamas deal: The hostage, ceasefire, and peace agreement could have a grim lesson for future wars.

    October 14, 2025

    Subscribe to Updates

    Get the latest technology news from Bigteetechhub about IT, Cybersecurity and Big Data.

      • About Us
      • Contact Us
      • Disclaimer
      • Privacy Policy
      • Terms and Conditions
      © 2025 bigteetechhub.All Right Reserved

      Type above and press Enter to search. Press Esc to cancel.