How to parse JSON in Swift using Codable protocol?

In this Swift tutorial, I'd like to give you an example about getting and parsing JSON data using URLSession and Codable protocol.



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. 🤔


If your task is simply to load some kind of JSON document through HTTP from around the web, - 🎁 suprise 🎁 - 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)")
    guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else {
        print("Error: invalid HTTP response code")
    guard let data = data else {
        print("Error: missing data")

    // 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( { $0.title })
    catch {
        print("Error: \(error.localizedDescription)")

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 coode. 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.

The Codable protocol - which is actually a compound typealias from Encodable & Decodable protocols - makes the process of parsing JSON data in Swift magical. 💫

To save some typing, you can also generate the final objects directly from the JSON structure with these amazing Xcode extensions.

Share this article on Twitter.
Thank you. 🙏

Picture of Tibor Bödecs

Tibor Bödecs

Creator of (weekly Swift articles), server side Swift enthusiast, full-time dad. -- Follow me & feel free to say hi. 🤘🏻 -- #iOSDev #SwiftLang

Twitter · GitHub


100% Swift news, delivered right into your mailbox

Updates about the latest Swift news including my articles and everything what happened in the Swift community as well.

Subscribe now