Monday, March 16, 2026
HomeiOS DevelopmentThe best way to parse JSON in Swift utilizing Codable protocol?

The best way to parse JSON in Swift utilizing Codable protocol?



· 1 min learn


On this Swift tutorial, I would like to present you an instance about getting and parsing JSON information utilizing URLSession and Codable protocol.

Dependencies

To begin with only a few phrases about dependencies. From Swift 4 you don’t want any dependency to parse JSON information, as a result of there are built-in protocols to care for all the pieces. If you’re nonetheless utilizing some sort of Third-party you need to positively ditch it for the sake of simplicity. By the way in which earlier than you add any exterior dependency into your mission, please suppose twice. 🤔

Networking

In case your job is solely to load some sort of JSON doc by way of HTTP from across the net, – shock – you received’t want Alamofire in any respect. You should utilize the built-in URLSession class to make the request, and get again all the pieces that you just’ll want. The Basis networking stack is already a posh and really helpful stack, don’t make issues much more sophisticated with additional layers.

JSON parsing

Now, after the quick intro, let’s dive in and get some actual faux JSON information from the JSONPlaceholder net service. I’m going to position the entire thing proper right here, you may choose it, copy and paste right into a Swift playground file.

import Basis
import PlaygroundSupport

PlaygroundPage.present.needsIndefiniteExecution = true

struct Put up: Codable {

    enum CodingKeys: String, CodingKey {
        case id
        case title
        case physique
        case userIdentifier = "userId"
    }

    let id: Int
    let title: String
    let physique: String
    let userIdentifier: Int
}

let url = URL(string: "https://jsonplaceholder.typicode.com/posts")!

URLSession.shared.dataTask(with: url) { information, response, error in
    if let error = error {
        print("Error: (error.localizedDescription)")
        PlaygroundPage.present.finishExecution()
    }
    guard 
        let httpResponse = response as? HTTPURLResponse, 
        httpResponse.statusCode == 200 
    else {
        print("Error: invalid HTTP response code")
        PlaygroundPage.present.finishExecution()
    }
    guard let information = information else {
        print("Error: lacking information")
        PlaygroundPage.present.finishExecution()
    }

    // be happy to uncomment this for debugging information
    // print(String(information: information, encoding: .utf8))

    do {
        let decoder = JSONDecoder()
        let posts = attempt decoder.decode([Post].self, from: information)

        print(posts.map { $0.title })
        PlaygroundPage.present.finishExecution()
    }
    catch {
        print("Error: (error.localizedDescription)")
        PlaygroundPage.present.finishExecution()
    }
}.resume()

As you may see downloading and parsing JSON from the net is a very easy job. This entire code snippet is round 50 strains of code. In fact it’s only a proof of idea, however it works and also you don’t want any dependency. It’s pure Swift and Basis.

NOTE: To save some typing, you may as well generate the ultimate objects straight from the JSON construction with these wonderful Xcode extensions.

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

Associated posts


Be taught all the pieces about logical varieties and the Boolean algebra utilizing the Swift programming language and a few fundamental math.


Learn to talk with API endpoints utilizing the model new SwiftHttp library, together with async / await assist.


The one and solely tutorial that you will ever have to be taught larger order features like: map, flatMap, compactMap, cut back, filter and extra.


Be taught the very fundamentals about protocols, existentials, opaque varieties and the way they’re associated to generic programming in Swift.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments