24.6 C
Canberra
Thursday, November 14, 2024

Tips on how 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 knowledge utilizing URLSession and Codable protocol.

Dependencies

To start with just some phrases about dependencies. From Swift 4 you don’t want any dependency to parse JSON knowledge, as a result of there are built-in protocols to handle all the pieces. In case you are nonetheless utilizing some sort of Third-party you must positively ditch it for the sake of simplicity. By the way in which earlier than you add any exterior dependency into your venture, please suppose twice. 🤔

Networking

In case your activity is just to load some sort of JSON doc by way of HTTP from across the net, – shock – you gained’t want Alamofire in any respect. You should use 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 fancy 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 pretend JSON knowledge from the JSONPlaceholder net service. I’m going to put 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 Submit: 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) { knowledge, 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 knowledge = knowledge else {
        print("Error: lacking knowledge")
        PlaygroundPage.present.finishExecution()
    }

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

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

        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 net is a very easy activity. This entire code snippet is round 50 traces of code. After all it’s only a proof of idea, but it surely works and also you don’t want any dependency. It’s pure Swift and Basis.

NOTE: To save some typing, you can even 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 knowledge in Swift magical. 💫

Associated posts


· 6 min learn


Study all the pieces about logical sorts and the Boolean algebra utilizing the Swift programming language and a few fundamental math.


· 4 min learn


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


· 9 min learn


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


· 5 min learn


Study the very fundamentals about protocols, existentials, opaque sorts 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

[td_block_social_counter facebook="tagdiv" twitter="tagdivofficial" youtube="tagdiv" style="style8 td-social-boxed td-social-font-icons" tdc_css="eyJhbGwiOnsibWFyZ2luLWJvdHRvbSI6IjM4IiwiZGlzcGxheSI6IiJ9LCJwb3J0cmFpdCI6eyJtYXJnaW4tYm90dG9tIjoiMzAiLCJkaXNwbGF5IjoiIn0sInBvcnRyYWl0X21heF93aWR0aCI6MTAxOCwicG9ydHJhaXRfbWluX3dpZHRoIjo3Njh9" custom_title="Stay Connected" block_template_id="td_block_template_8" f_header_font_family="712" f_header_font_transform="uppercase" f_header_font_weight="500" f_header_font_size="17" border_color="#dd3333"]
- Advertisement -spot_img

Latest Articles