JSON 轉 Swift 產生器

JSON 輸入

正在載入編輯器…

生成的 Swift

Configuration

輸入 JSON 資料以產生 Swift struct

具備 Codable 與型別安全的 struct

如何將 JSON 轉換為 Swift – 步驟指南

使用此 JSON 轉 Swift 產生器,可從 JSON 範例產生符合 Codable 的 Swift struct,適合 iOS/macOS 與 Swift 服務。

  1. 步驟 1 – 貼上 JSON 範例

    • 將具有代表性的 JSON 物件或陣列貼到左側編輯器。
    • 盡量包含巢狀物件、陣列與可為 null 的欄位,方便正確推斷型別。
    • 使用 匯入 從檔案、URL 或示例資料載入 JSON。
  2. 步驟 2 – 選擇 Swift struct 選項

    • 設定根 Struct Name(例如 Root)。
    • 確認可選欄位對應到 String? 等可為 null 的型別。
    • JSON key 與 Swift 命名不同時,確認 key 對應策略。
  3. 步驟 3 – 檢查產生的程式碼

    • 確認欄位命名、型別推斷,以及陣列/物件的對應方式是否符合預期。
    • 依需求調整 根型別名稱、null 處理策略與可選的框架選項。
    • 若某些欄位推斷不準確,優化 JSON 範例後重新產生。
  4. 步驟 4 – 使用 Codable 解析 JSON

    • 將 struct 加入專案並確保遵循 Codable
    • 使用 JSONDecoder 將 JSON 解碼為根 struct。
    • 依需求加入 CodingKeys 或日期解碼策略。
  5. 步驟 5 – 複製或下載

    • 將輸出複製到專案中,或下載成檔案。
    • 執行格式化/程式碼檢查工具,讓風格與專案一致。
    • 若目標語言需要序列化/解析函式庫,請在專案中加入相依套件。

快速提示

  • 時間欄位可用 JSONDecoder.dateDecodingStrategy 搭配 ISO8601。
  • 需要 snake_case 轉 camelCase 時,使用 CodingKeys 或 keyDecodingStrategy。
  • 讓 DTO 與 UI model 分離,降低耦合。
範例輸出(簡化)
// JSON 輸入
{
  "id": 123,
  "name": "Maeve Winters",
  "email": "[email protected]",
  "active": true,
  "roles": ["admin", "editor"],
  "metadata": { "plan": "pro" },
  "createdAt": "2024-03-01T10:15:00Z",
  "score": 99.5,
  "notes": null
}

// 產生的 Swift 模型(簡化)
struct Metadata: Codable {
  let plan: String
}

struct Root: Codable {
  let id: Int
  let name: String
  let email: String?
  let active: Bool
  let roles: [String]
  let metadata: Metadata
  let createdAt: String
  let score: Double
  let notes: String?
}

相關 JSON 與 Swift 工具

探索更多可與本 JSON 轉 Swift 產生器搭配使用的 JSON 與 Schema 工具。

常見問題

支援哪些 Swift 特性?

產生器會建立具備型別安全的 Swift struct,支援 Codable 協定進行 JSON 序列化/反序列化,使用 optional 型別處理 null 值,並遵循 Swift 命名慣例。

Codable 協定如何運作?

選擇 Codable 框架時,產生的 struct 會自動符合 Codable 協定,可用 JSONEncoder 與 JSONDecoder 進行 JSON 編碼/解碼。

optional 值如何處理?

JSON 中的 null 值會對應到 Swift 的 optional 型別(?),需要明確 unwrap,符合 Swift 對 null safety 的做法。

Swift 的型別系統呢?

產生的程式碼會使用適當型別(Int、Double、String、Bool、[Any]、[String: Any]),並以 struct 的 value semantics 建立不可變資料模型。

JSON 轉 Swift 產生器 | JSONSwiss