Swift JSON 解析指南
概述
在 Swift 中,我們可以使用 JSONDecoder 將 JSON 字串轉換為 Swift 物件。這篇文章將詳細介紹如何使用 Decodable protocol 和 JSONDecoder 來處理 JSON 資料。
基本概念
Codable Protocol 家族
Encodable:能被轉成 JSON(或其他格式)Decodable:能從 JSON(或其他格式)轉回 Swift 型別Codable:同時繼承了Encodable和Decodable
JSONDecoder 的用法
JSONDecoder().decode() 的簽名是這樣的:
func decode<T>(_ type: T.Type, from data: Data) throws -> T where T : Decodable
使用 JSONDecoder 需要三個步驟:
- 定義一個遵守
Decodableprotocol 的結構或類別(model) - 準備
Data(通常是從 JSON string 轉成 Data) - 使用
decode()方法轉換為 Swift 物件
完整範例
1. 定義 Model
struct Person: Decodable {
let name: String
let age: Int
}
2. JSON 資料
{
"name": "Thomas",
"age": 30
}
3. 轉換過程
import UIKit
// JSON 字串
let jsonString = """
{
"name": "Thomas",
"age": 30
}
"""
// 把 JSON string 轉成 Data
let data = jsonString.data(using: .utf8)!
// decode 成 Swift struct
let person = try! JSONDecoder().decode(Person.self, from: data)
// 使用轉換後的物件
print(person.name) // "Thomas"
print(person.age) // 30
常見錯誤與修正
錯誤的寫法
data()
let config = try! JSONDecoder().decode()
正確的寫法
let data = ... // 這裡要是 Data,可能是從檔案或 API 拿到
let config = try! JSONDecoder().decode(Config.self, from: data)
其中 Config 要先定義好:
struct Config: Decodable {
let url: String
let timeout: Int
}
重要特性
Swift 自動生成 Decodable
只要你的 struct 所有屬性都是 Decodable 的型別(像是 String, Int, Bool, Double, 甚至其他 Decodable struct),Swift 會自動幫你生成 Decodable 的實作,你不用自己寫。
錯誤處理
建議使用 do-catch 來處理可能的錯誤:
do {
let person = try JSONDecoder().decode(Person.self, from: data)
print(person.name)
} catch {
print("解析失敗: \(error)")
}
總結
使用 Swift 解析 JSON 的關鍵步驟:
- 定義遵守
Decodableprotocol 的 model - 將 JSON 字串轉換為
Data - 使用
JSONDecoder().decode()進行轉換 - 適當處理可能的錯誤
這樣就能輕鬆地在 Swift 中處理 JSON 資料了!