首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

Swift 解析嵌套 JSON:使用 Codable 協議建模數據結構

     編輯:程式設計疑難解答

問題場景

接口返回嵌套 JSON,包含頂層字段 (text) 及嵌套對象 user (含 screen_name, profile_image_url)。需要定義 Model 映射並展示在 TableView 中。

現代最佳實踐:Swift Codable (Swift 4+)

拒絕手動字典解析 (SwiftyJSON 等第三方庫),原生 Codable 類型安全、效能高、代碼極少。

1. 定義模型結構

struct Status: Codable {
    let createdAt: String
    let id: Int64
    let text: String
    let user: User       // 嵌套模型
    // 其他字段...
    
    // 鍵名映射 (JSON snake_case -> Swift camelCase)
    enum CodingKeys: String, CodingKey {
        case createdAt = "created_at"
        case id
        case text
        case user
        // ...
    }
}

struct User: Codable {
    let id: Int64
    let screenName: String
    let profileImageUrl: String
    let avatarLarge: String?
    // 其他字段...
    
    enum CodingKeys: String, CodingKey {
        case id
        case screenName = "screen_name"
        case profileImageUrl = "profile_image_url"
        case avatarLarge = "avatar_large"
    }
}

// 頂層響應包裝
struct APIResponse: Codable {
    let total: Int
    let success: Bool
    let rows: [Status]  // 直接映射數組
    // metaData 等其他字段...
}

2. 解碼與使用

let decoder = JSONDecoder()
// 可選:日期格式化策略
// decoder.dateDecodingStrategy = .iso8601 

do {
    let response = try decoder.decode(APIResponse.self, from: jsonData)
    let statuses = response.rows
    
    // 更新 TableView
    DispatchQueue.main.async {
        self.dataSource = statuses
        self.tableView.reloadData()
    }
} catch {
    print("JSON 解析失敗: \(error)")
    // error 會精確指出缺失字段、類型不匹配等
}

3. TableView Cell 配置

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
    let status = dataSource[indexPath.row]
    
    cell.textLabel?.text = status.text
    cell.detailTextLabel?.text = status.user.screenName
    
    // 異步加載圖片 (建議使用 Kingfisher/SDWebImageSwift)
    if let url = URL(string: status.user.profileImageUrl) {
        cell.imageView?.kf.setImage(with: url, placeholder: UIImage(named: "placeholder"))
    }
    return cell
}

進階技巧

  • 字段可選性: API 字段可能缺失,Model 中標記為 let field: String?,解碼不會崩潰。
  • 嵌套數組: medpresinfo 這類字符串內嵌 JSON,需二次解碼:
    let prescriptions = try decoder.decode([Prescription].self, from: status.medpresinfo.data(using: .utf8)!)
  • Key 映射自動化: 使用 keyDecodingStrategy = .convertFromSnakeCase 可省去大部分 CodingKeys 手寫。

總結

Swift 原生 Codable 完美解決嵌套 JSON 建模,結構清晰、編譯時檢查、無需第三方依賴。配合異步圖片加載庫,即可高效構建列表展示界面。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved