Skip to Content
Course content

40: Working with JSON in Swift

Click on the "Edit" button in the top corner of the screen to edit your slide content.

At some point in your career, you're going to have to pull data from a web API. Almost every modern API speaks JSON, and if you've spent any time in JavaScript or Python, you're probably used to just treating JSON as a giant, flexible dictionary. When you first move into Swift, it's tempting to bring that same mindset with you. I've seen plenty of developers try to "brute force" their way through JSON parsing because they didn't want to spend time defining models for data they thought was simple.

The fragility of casting everything

The "naive" way to handle JSON in Swift is using JSONSerialization. This approach basically turns your JSON string into a Any type—usually a [String: Any] dictionary—and then leaves you to figure out what's inside. Let's say we're building a weather app and the API gives us a response like this: {"city": "Seattle", "temp": 55, "conditions": "Rainy"}.

let jsonData = jsonString.data(using: .utf8)!
if let dictionary = try? JSONSerialization.jsonObject(with: jsonData) as? [String: Any] {
    if let city = dictionary["city"] as? String {
        print("The weather in \(city) is...")
    }
    if let temp = dictionary["temp"] as? Int {
        print("It is \(temp) degrees.")
    }
}

On the surface, this looks fine. But as a professional, this makes me nervous. Why? Because you're relying on "stringly-typed" code. If the API provider changes "city" to "cityName", your code doesn't crash, but the if let fails silently and your UI just stays empty. Even worse, you're casting types manually everywhere. If the API suddenly starts sending the temperature as a double (55.5) instead of an integer, your as? Int cast fails, and your app "breaks" even though the data is technically still there. It's a maintenance nightmare that scales poorly the moment your JSON gets nested.

Letting the compiler do the heavy lifting

The better way—and the way you should be doing this in any production app—is using the Codable protocol. Instead of treating the JSON as a bag of mystery values, we define a blueprint of what we expect. By creating a struct that conforms to Decodable, we tell Swift exactly how the data should look. If the data doesn't match the blueprint, the decoder throws a clear error telling us exactly which key was missing or which type was mismatched.

struct WeatherResponse: Codable {
    let city: String
    let temp: Int
    let conditions: String
}

let decoder = JSONDecoder()
do {
    let weather = try decoder.decode(WeatherResponse.self, from: jsonData)
    print("The weather in \(weather.city) is \(weather.temp) degrees.")
} catch {
    print("Decoding failed: \(error)")
}

Now, we have type safety. We aren't guessing if temp is an Int; the compiler guarantees it. If the API changes and city disappears, the catch block triggers immediately, letting us know exactly what went wrong during development rather than hunting for a silent bug in production.

Bridging the gap between API style and Swift style

Here is where things usually get tricky: APIs rarely follow Swift's camelCase naming conventions. You'll often encounter snake_case keys like current_temperature. You could name your Swift properties current_temperature to match, but that feels wrong in a Swift codebase. I hate seeing snake_case in my structs; it just looks out of place.

You have two choices here. The "quick" way is to tell the JSONDecoder to convert snake_case automatically using .convertFromSnakeCase. But if the API names are truly erratic (like Temp_Val_2023), that won't help. In those cases, we use CodingKeys. This is a special enum inside your struct that maps the JSON key name to your preferred Swift property name.

struct WeatherResponse: Codable {
    let city: String
    let temperature: Int

    enum CodingKeys: String, CodingKey {
        case city
        case temperature = "temp_val"
    }
}

This approach gives you the best of both worlds. You keep your Swift code clean and idiomatic, while still being able to consume data from a backend that might have been written in a completely different language or era. It moves the "translation" logic into a single, declarative place rather than scattering as? casts throughout your view controllers.




📋 Practical Task

Exercise: Building a Movie Metadata Parser

You've been given a JSON response from a movie database API. Your task is to create a type-safe way to parse this data. The API returns the following JSON string:

"{"movie_title": "Inception", "release_year": 2010, "director": {"name": "Christopher Nolan", "nationality": "British"}}"

Requirements:

  • Create a Director struct and a Movie struct that conform to Codable.
  • Use CodingKeys to map movie_title to a Swift property named title and release_year to year.
  • The Director struct should be nested inside the Movie struct.
  • Write the code to decode a JSON string into your Movie struct using JSONDecoder.
  • Print the director's name and the movie title to the console to verify it works.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.