The way to parse JSON in Swift utilizing Codable protocol?

0/5 No votes

Report this app



JSON parsing

Now, after the quick intro, let’s dive in and get some actual faux JSON knowledge from the JSONPlaceholder net service. I will place the entire thing proper right here, you possibly can 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: "")!

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


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

        print( { $0.title })
    catch {
        print("Error: (error.localizedDescription)")

As you possibly can see downloading and parsing JSON from the net is a very easy process. This complete code snippet is round 50 traces of coode. In fact it is only a proof of idea, but it surely works and you do not want any dependency. It is pure Swift and Basis.

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

To save some typing, you may also generate the ultimate objects instantly from the JSON construction with these wonderful Xcode extensions.


Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.