JSON 輸入
生成的 Swift
輸入 JSON 資料以產生 Swift struct
具備 Codable 與型別安全的 struct
從 JSON 資料產生具備 Codable 支援的 Swift struct
輸入 JSON 資料以產生 Swift struct
具備 Codable 與型別安全的 struct
使用此 JSON 轉 Swift 產生器,可從 JSON 範例產生符合 Codable 的 Swift struct,適合 iOS/macOS 與 Swift 服務。
步驟 1 – 貼上 JSON 範例
匯入 從檔案、URL 或示例資料載入 JSON。步驟 2 – 選擇 Swift struct 選項
Struct Name(例如 Root)。String? 等可為 null 的型別。步驟 3 – 檢查產生的程式碼
根型別名稱、null 處理策略與可選的框架選項。步驟 4 – 使用 Codable 解析 JSON
Codable。JSONDecoder 將 JSON 解碼為根 struct。CodingKeys 或日期解碼策略。步驟 5 – 複製或下載
快速提示
JSONDecoder.dateDecodingStrategy 搭配 ISO8601。CodingKeys 或 keyDecodingStrategy。// 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 與 Schema 工具。
產生器會建立具備型別安全的 Swift struct,支援 Codable 協定進行 JSON 序列化/反序列化,使用 optional 型別處理 null 值,並遵循 Swift 命名慣例。
選擇 Codable 框架時,產生的 struct 會自動符合 Codable 協定,可用 JSONEncoder 與 JSONDecoder 進行 JSON 編碼/解碼。
JSON 中的 null 值會對應到 Swift 的 optional 型別(?),需要明確 unwrap,符合 Swift 對 null safety 的做法。
產生的程式碼會使用適當型別(Int、Double、String、Bool、[Any]、[String: Any]),並以 struct 的 value semantics 建立不可變資料模型。