Close Menu
geekfence.comgeekfence.com
    What's Hot

    Duck Creek is entering its operating model era

    April 29, 2026

    Sparse AI Hardware Slashes Energy and Latency

    April 29, 2026

    Rogers to offer voluntary buyouts to 10,000 employees

    April 29, 2026
    Facebook X (Twitter) Instagram
    • About Us
    • Contact Us
    Facebook Instagram
    geekfence.comgeekfence.com
    • Home
    • UK Tech News
    • AI
    • Big Data
    • Cyber Security
      • Cloud Computing
      • iOS Development
    • IoT
    • Mobile
    • Software
      • Software Development
      • Software Engineering
    • Technology
      • Green Technology
      • Nanotechnology
    • Telecom
    geekfence.comgeekfence.com
    Home»iOS Development»How to parse JSON in Swift using Codable protocol?
    iOS Development

    How to parse JSON in Swift using Codable protocol?

    AdminBy AdminMarch 29, 2026No Comments3 Mins Read2 Views
    Facebook Twitter Pinterest LinkedIn Telegram Tumblr Email
    How to parse JSON in Swift using Codable protocol?
    Share
    Facebook Twitter LinkedIn Pinterest Email


    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?

    9/27/25 11:00 AM
    · 6 min read


    Discover how traits act as feature flags, enabling conditional compilation, optional dependencies, and advanced package configurations.

    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.



    Source link

    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email

    Related Posts

    ios – AppShortcut is shown in Shortcuts app but not in Spotlight

    April 29, 2026

    How to make a Swift framework?

    April 25, 2026

    ios – AVCaptureDevice.exposurePointOfInterest readback does not match set value on iPad Pro M4 / M3(UltraWide)and Gen2,3,4(TrueDepth) using resizeAspectFill

    April 24, 2026

    How I use FlowDeck to let my AI agent build and run my apps – Donny Wals

    April 21, 2026

    DTCoreText 2.0 | Cocoanetics

    April 20, 2026

    How to launch a macOS app at login?

    April 19, 2026
    Top Posts

    Understanding U-Net Architecture in Deep Learning

    November 25, 202533 Views

    Hard-braking events as indicators of road segment crash risk

    January 14, 202626 Views

    Redefining AI efficiency with extreme compression

    March 25, 202625 Views
    Don't Miss

    Duck Creek is entering its operating model era

    April 29, 2026

    Many Duck Creek programs are discovering that the hardest part in modernization begins after go-live.…

    Sparse AI Hardware Slashes Energy and Latency

    April 29, 2026

    Rogers to offer voluntary buyouts to 10,000 employees

    April 29, 2026

    Evolving image recognition with Geometric Deep Learning

    April 29, 2026
    Stay In Touch
    • Facebook
    • Instagram
    About Us

    At GeekFence, we are a team of tech-enthusiasts, industry watchers and content creators who believe that technology isn’t just about gadgets—it’s about how innovation transforms our lives, work and society. We’ve come together to build a place where readers, thinkers and industry insiders can converge to explore what’s next in tech.

    Our Picks

    Duck Creek is entering its operating model era

    April 29, 2026

    Sparse AI Hardware Slashes Energy and Latency

    April 29, 2026

    Subscribe to Updates

    Please enable JavaScript in your browser to complete this form.
    Loading
    • About Us
    • Contact Us
    • Disclaimer
    • Privacy Policy
    • Terms and Conditions
    © 2026 Geekfence.All Rigt Reserved.

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