iOS JSON 解析
與伺服器溝通時,最常交換的資料格式就是 JSON。在 Swift 中,我們使用 Codable (Encodable & Decodable) 協議與 JSONDecoder 來輕鬆轉換 JSON 資料。
定義資料模型 (Model)
假設伺服器回傳的 JSON 如下:
{
"id": 1,
"name": "John Doe",
"email": "john@example.com",
"is_active": true
}
我們需要定義一個對應的 Struct,並遵循 Codable。
struct User: Codable, Identifiable {
let id: Int
let name: String
let email: String
let isActive: Bool // 注意命名風格差異 (CamelCase vs SnakeCase)
}
JSONDecoder
使用 JSONDecoder 將 Data 轉換成 Struct。
let jsonData = getJsonData() // 假設這是從網路拿到的 Data
let decoder = JSONDecoder()
// 策略:自動將 JSON 的 snake_case 轉成 Swift 的 camelCase
decoder.keyDecodingStrategy = .convertFromSnakeCase
do {
let user = try decoder.decode(User.self, from: jsonData)
print("用戶名: \(user.name)")
} catch {
print("解析失敗: \(error)")
}
常見問題
1. 欄位可以為空 (Optional)
如果 JSON 中某個欄位可能不存在或為 null,Struct 中的屬性必須宣告為 Optional (String?)。
2. 自定義欄位名稱 (CodingKeys)
如果 convertFromSnakeCase 無法滿足需求,你可以手動定義映射關係。
struct Product: Codable {
let price: Double
let description: String
enum CodingKeys: String, CodingKey {
case price = "product_price" // JSON key 是 "product_price"
case description // 名稱一樣可省略值
}
}
學會 JSON 解析後,結合前面的 Concurrency,我們就可以開始撰寫真正的網路請求程式碼了。