本文へスキップ
BecomeCoder

Swift(iOSアプリ)コース · 第8章 データ・通信・公開 ― 実機で仕上げる · レッスン34

Codable ― JSONをSwiftの型に変換する

ローカル実施

導入

サーバーから届くデータの多くは JSON という形式の文字列です。それをSwiftの struct にサッと変換してくれるのが Codable です。

説明

JSONはこんな見た目のテキストです。

{ "name": "田中", "age": 28 }

これを受け取る struct を Codable に準拠させると、SwiftがJSONと struct を自動で相互変換してくれます。プロパティ名をJSONのキーに合わせるのがコツです。

struct User: Codable {
    let name: String
    let age: Int
}

let json = "{\"name\":\"田中\",\"age\":28}"
let data = json.data(using: .utf8)!
let user = try JSONDecoder().decode(User.self, from: data)
print(user.name)   // 田中

JSONDecoder().decode(User.self, from: data) が「このJSONを User として読み解いて」という命令。逆に、structからJSONを作るには JSONEncoder を使います。

第33章の通信で受け取った data を、この Codableモデルに変換する――これが「サーバーからデータを取ってアプリで使う」王道の流れです。

graph LR
  A["サーバー"] -->|"JSON文字列"| B["URLSession<br/>で受信"]
  B -->|"Codable でデコード"| C["Swiftのstruct<br/>User(name, age)"]
  C --> D["SwiftUIで表示"]

まとめ

  • サーバーのデータは多くが JSON
  • struct を Codable にすると、JSON ⇄ struct を自動変換できる。
  • 通信(URLSession)+変換(Codable)+表示(SwiftUI)が定番の流れ。