0Pricing
Swift Academy · Lesson

Decoding with JSONDecoder

Parse JSON data into typed Swift values.

Creating a JSONDecoder

JSONDecoder rebuilds a Swift value from JSON Data. You tell it the type to produce and hand it the bytes.

import Foundation

struct City: Codable {
    var name: String
    var population: Int
}

let json = "{\"name\":\"Oslo\",\"population\":700000}"
let data = json.data(using: .utf8)!
let city = try JSONDecoder().decode(City.self, from: data)
print(city.name, city.population)

Passing the Type with .self

The first argument is the metatype — written MyType.self. This tells the decoder which structure to build from the data.

import Foundation

struct Flag: Codable { var ok: Bool }

let data = "{\"ok\":true}".data(using: .utf8)!
let result = try JSONDecoder().decode(Flag.self, from: data)
print(result.ok)

All lessons in this course

  1. Conforming to Codable
  2. Encoding with JSONEncoder
  3. Decoding with JSONDecoder
  4. Handling Optional and Nested Types
← Back to Swift Academy