Thursday, July 4, 2024
HomeIOS DevelopmentHow one can parse JSON in Swift utilizing Codable protocol?

How one can parse JSON in Swift utilizing Codable protocol?


Dependencies

To start with only a few phrases about dependencies. From Swift 4 you do not want any dependency to parse JSON information, as a result of there are built-in protocols to handle all the things. If you’re nonetheless utilizing some form of Third-party it is best to positively ditch it for the sake of simplicity. By the best way earlier than you add any exterior dependency into your venture, please assume twice. 🤔

Networking

In case your process is solely to load some form of JSON doc via HTTP from across the internet, – shock – you will not want Alamofire in any respect. You should use the built-in URLSession class to make the request, and get again all the things that you’re going to want. The Basis networking stack is already a posh and really helpful stack, do not make issues much more difficult with additional layers.

JSON parsing

Now, after the brief intro, let’s dive in and get some actual faux JSON information from the JSONPlaceholder internet service. I’ll place the entire thing proper right here, you’ll be able to choose it, copy and paste right into a Swift playground file.

import Basis
import PlaygroundSupport

PlaygroundPage.present.needsIndefiniteExecution = true

struct Publish: 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()
    }

    

    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’ll be able to see downloading and parsing JSON from the online is a very easy process. This complete code snippet is round 50 traces of code. After all it is only a proof of idea, however it works and you do not want any dependency. It is pure Swift and Basis.

To save some typing, you may also generate the ultimate objects instantly from the JSON construction with these superb 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. 💫

RELATED ARTICLES

Most Popular

Recent Comments